2017-01-13 30 views
0

做一個不明高度垂直的img中部,CSS和支持IE9

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

 
img { 
 
    width : 100%; 
 
    }
<div class="box"> 
 
    <img src="banner.png" /> 
 
</div>

我不知道圖像banner.png的大小,但我想限制.boxmax-height。如果banner.png的高度大於max-height,我需要使img標籤垂直居中。

我該如何做到這一點?

回答

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

試着像這樣笑話。

更新答案

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

非常感謝你。但我不想改變圖像的大小。 – LCB

+0

我已更新我的代碼。請檢查。它的工作沒有改變圖像高度 –

0

使用試試這個代碼柔性

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

+0

謝謝。因爲我需要支持IE9,可能是'display:flex;'在IE9中無法工作。 – LCB

+0

使用IE –

+0

的更新版本看看是的,我試過這種方式,但如果我沒有指定'.box'元素的高度,則img的位置不正確。 – LCB

0

試試這個

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

.box img { 
    margin: auto; 
} 
+0

Flex屬性在IE中不起作用 –

+0

從10開始http://caniuse.com/#search=flexbox IE9很少用戶 – grinmax

+0

我的意思是在IE 9中按照每個問題 –