用CSS做一个不知道的高度img垂直中间,并支持IE9



.box {
    width : 100%;
    max-height : 300px;
    overflow : hidden; 
}
img {
     width : 100%;
    }
<div class="box">
    <img src="banner.png" />
</div>

我不知道图像横幅的大小.png但我想限制.box元素的max-height。如果横幅.png的高度大于max-height我需要使img标签垂直居中。

我怎么做呢?

.box{
width : 100%;
max-height : 300px;
overflow : hidden;
}
.box > img {
    width : 100%;
    max-width:100%;
    vertical-align:middle;
}

试着像这样闷闷不乐。

更新的答案

.box {
 width : 100%;
 max-height : 300px;
 overflow : hidden;
}
.box img {
 width:100px;
 vertical-align: middle;
}

使用 flex 尝试此代码

.box{
width : 100%;
max-height : 300px;
display:flex;
align-items: center;
}

.box {
    width : 100%;
    min-height : 300px;
    overflow : hidden;
    border:1px solid green; 
    display:flex;
    align-items:center;
}
<div class="box">
    <img src="http://c5.la4.download.9appsinstall.com:7080/group1/M02/6D/74/pYYBAFhLFviAdm8mAAAWl_5Xbaw477.png" />
</div>

使用位置

.box {
    width : 100%;
    min-height : 300px;
    overflow : hidden;
    border:1px solid green; 
    display:block;
    position:relative;
}
.box img {
    position:absolute;
    top:50%;
    transform: translate(0, -50%)
}
<div class="box">
    <img src="http://c5.la4.download.9appsinstall.com:7080/group1/M02/6D/74/pYYBAFhLFviAdm8mAAAWl_5Xbaw477.png" />
</div>

试试这个

.box {
    width : 100%;
    max-height : 300px;
    overflow : hidden; 
    display: flex;
}
.box img {
    margin: auto;
}

最新更新