css中如何实现图片垂直居中显示?

css中如何实现图片垂直居中显示?下面本篇文章就来给大家介绍一下使用CSS实现图片垂直居中的方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

一、使用flex实现图片垂直居中

利用 display:flex; align-items:center;实现垂直居中。flex可能不是实现垂直居中最好的选择,因为IE8,9并不支持它。

html代码:

<div class="flexbox">
    <img src="1.jpg-600" alt="">
</div>

css代码:

body{ background:#999}
.flexbox{width: 300px;height: 250px;background:#fff;display: flex;align-items: center}
.flexbox img{width: 100px;height: 100px;align-items: center;}

二、利用display:table;实现img图片垂直居中

给最外层的div设置display属性为table;img的父元素div设置display:table-cell,vertical-align: middle;如果你也想实现水平居中,你可以给最外层的div元素添加text-align: center属性

html代码:

<div class="tablebox">
    <div id="imgbox">
        <img src="1.jpg-600" alt="">
    </div>
</div>

css代码:

.tablebox{width: 300px;height: 250px;background: #fff;display: table}
#imgbox{display: table-cell;vertical-align: middle;}
#imgbox img{width: 100px}

三、用绝对定位实现垂直居中(推荐-兼容性好)

1、给img的父元素添加相对定位属性(position: relative),同时,要给子元素也就是图片img元素添加绝对定位属性(position: absolute)。

2、将图片元素的top属性设置为50%。

3、现在我们需要给img元素设置一个负的margin-top值,这个值为你想要实现垂直居中的元素高度的一半,*如果不确定元素的高度,可以不使用margin-top,而是使用transform:translateY(-50%);属性。

记住:如果你想要同时实现水平居中,那么你可以用实现垂直居中的一样的技巧来实现。

HTML代码:

<div class="posdiv">
    <img src="1.jpg-600" alt="">
</div>

css代码:

body{background: #ccc;}
.posdiv{width: 300px;height: 250px;background: #fff;position: relative; margin:0 auto}
.posdiv img{width: 100px;position: absolute;top: 50%;margin-top: -50px;}

更多CSS相关知识,可访问 CSS教程 !!

以上就是css中如何实现图片垂直居中显示?的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » CSS3 答疑