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

2020-07-23 22:05:36
在页面布局时经常需要对图片的位置进行处理,这篇文章围绕图片居中展开,主要讲了如何用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>

效果图:

图片垂直居中1.jpg

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.jpg

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种方法,各不相同,具体用什么方法,看个人习惯和工作需要,初学者可以自己动手尝试,希望可以帮助到你!