您好,欢迎来到易妖游戏网。
搜索
您的当前位置:首页图文详解图片水平垂直居中的五种方法(附代码)

图文详解图片水平垂直居中的五种方法(附代码)

来源:易妖游戏网
 在页面布局时经常需要对图片的位置进行处理,这篇文章围绕图片居中展开,主要讲了如何用CSS实现图片的水平居中,图片垂直居中,还有图片的水平垂直居中,课程比较实用,感兴趣的小伙伴,可以参考一下,希望对你有所帮助。

1、text-align: center实现图片水平居中

text-align一般用于文本的水平居中,也可以用于图片,代码如下:

CSS部分:

<style type="text/css">
 div{
 text-align: center;
 width: 500px; 
 border: green solid 1px;
 }
</style>

HTML部分:

<div>
 <img src="img/logo.png" />
</div>

效果图:

2、line-height和text-align: center 实现图片的水平垂直居中

设置line-height的值等于height,可以实现垂直居中,text-align: center可以实现水平居中。HTML部分一样,CSS代码如下:

<style type="text/css">
div{
text-align: center; 
width: 400px;
height:200px; 
line-height:200px; 
border: green solid 1px;
}
img{
vertical-align: middle;
}
</style>

效果图:

3、display: table和display: table-cell实现图片水平垂直居中

利用table方法设置display: table,display: table-cell,但是这种方法并不兼容IE6/IE7,如果你不需要支持IE67可以使用这种方法

css样式直接写在标签里面,代码如下:

<div style="text-align: center; width: 400px;height:200px; display: table;border: green solid 1px;">
 <span style="display: table-cell; vertical-align: middle; ">
 <img src="img/logo.png" />
 </span>
</div>

4、position实现图片水平垂直居中

定位方法:在父盒子中设置相对定位,在子盒子中设置绝对定位,即所谓的父相对子绝对。设置图片位置左边为50%,上边为50%,(注意:这样并没有垂直居中),还需要设置margin-left为图片长度的一半,margin-top为图片高度的一半。HTML部分一样,CSS代码如下;

<style type="text/css">
div{
width: 400px;
height:200px; 
position: relative;
border: green solid 1px;
}
img{
width: 200px;
height: 50px;
position: absolute;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -25px;
}
</style>

5、背景background实现图片水平垂直居中

利用background: url no-repeat center center 实现图片的水平垂直居中

div{
width: 400px;
height:200px; 
border: green solid 1px;
background: url(img/logo.png) no-repeat center center ;
}

总结:以上介绍了图片居中的5种方法,各不相同,具体用什么方法,看个人习惯和工作需要,初学者可以自己动手尝试,希望可以帮助到你!

Copyright © 2019- vipyiyao.com 版权所有 湘ICP备2023022495号-8

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务