精美而实用的网站,关注web编程技术、网站运营、SEO推广,让您轻松愉快的学习

图片在div里水平居中是非常简单的,但是在垂直居中方面就不是那么容易了,青岛星网下面跟大家分享:img图片在div里垂直居中的最佳解决方案,使用Flexbox来垂直居中图片。

HTML代码部分

<div class="qdxwimg"><img src="http://www.qdxw.net/images/logo2.gif" alt="使用Flexbox来使图片居中"></div>

CSS代码部分

.qdxwimg { 
     display: flex; 
    justify-content: center; 
    align-items: center; height:300px; background:#00CC99;
}
.qdxwimg img {height: auto; }

运行结果

flexbox也许是最简单的解决图片垂直居中的方法,但是由于一些旧语法和它缺乏对较早版本的IE浏览器的支持(可以使用display: table-cell 来解决IE问题),我们需要编写更多的代码,完整代码如下:

.center { 
    background: hsl(240, 100%, 97%);
    display: -webkit-box; /* OLD: Safari, iOS 6 and earlier; Android browser, older WebKit */
    display: -moz-box; /* OLD: Firefox (can be buggy) */
    display: -ms-flexbox; /* OLD: IE 10 */
    display: -webkit-flex; /* FINAL, PREFIXED, Chrome 21+ */
    display: flex; /* FINAL: Opera 12.1+, Firefox 22+ */
    -webkit-box-align: center;
    -moz-box-align: center;
    -ms-flex-align: center;
    -webkit-align-items: center;
    align-items: center;
    -webkit-box-pack: center;
    -moz-box-pack: center;
    -ms-flex-pack: center;
    -webkit-justify-content: center;
    justify-content: center;
}

使用table-cell来居中元素的方法

使用 display: table-cell,而不是实际的表格标签。它允许在水平和垂直两个方向上居中。使用这种方法通常需要添加和操纵一个外围包裹元素。这个元素可以是任何元素

HTML代码部分

<div class="center-aligned">
    <div class="center-core">
        <img src="jimmy-choo-shoe.jpg">
    </div>
</div>

CSS代码部分

.center-aligned { 
    display: table; 
    background: hsl(120, 100%, 97%); 
    width: 100%; 
}
.center-core { 
    display: table-cell; 
    text-align: center; 
    vertical-align: middle; 
}
.center-core img { width: 33%; height: auto; }

青岛星网提醒:width: 100%是必须的,它能阻止div收缩。为了垂直居中外部容器需要设置一些高度。如果想在body中垂直居中,就需要设置body和html元素的高度。该技术可以在所有的浏览器中使用,包括IE8。

Tags:CSS 垂直居中 Flexbox