
如圖所示,我們需要實現這樣一種效果,圖片img的高度是未知的(但高度還是小於外層box的高度)。HTML結構如下:
<div class="box">
<img src="http://img1.gtimg.com/nice_mb/08/1c/24769.jpg" />
</div>
CSS中跟元素垂直對齊有關的屬性是vertical-align,W3C中說,在單元格中這個屬性會設置單元格框中的內容的對齊方式。也就是說通過把一個DIV元素設置為單元格,然后就可以控制其中內容的顯示方式了。
.box{
width:200px;
height:200px;
border:1px solid #06C;
display:table-cell;
text-align:center;
vertical-align:middle;
}
此時除IE6\IE7之外,其他主流瀏覽器中基本上實現了圖片的垂直居中對齊。

由於IE6\IE7不支持display:table-cell, 只好想其他辦法來讓圖片實現垂直居中對齊。首先需要對DIV設置 *display:block ,利用淘寶工程師貢獻了一種方法,通過設置DIV的font-size來實現垂直居中,當元素的高度/字體大小=1.14左右的時候圖片能夠垂直居中(經過測試發現也與font-family有關)。完整CSS如下:
.box{
width:200px;
height:200px;
border:1px solid #06C;
display:table-cell;
text-align:center;
vertical-align:middle;
*font-family:simsun;*font-size:200px;
}
.box img{
vertical-align:middle;
}
最終效果如圖所示:

補充方法:定義定位實現未知高度元素的垂直居中(兼容IE5.5\6\7\8\9\10 firefox chrome)
需要在以上基礎上改變HTML結構,把img放在一個元素中間,如下:
<div class="box">
<p>
<img src="http://img1.gtimg.com/nice_mb/08/1c/24769.jpg" />
</p>
</div>
在支持display為table-cell的瀏覽器中依然用vertical-align:middle來實現,在IE5.5\IE6\IE7中利用定位來實現垂直居中,具體代碼如下:
.box {
border: 1px dashed #ccc;
height: 200px;
width: 200px;
overflow: hidden;
display: table-cell;
vertical-align: middle;
*position:relative;
}
p {
*position:absolute;
*top:50%;
width: 100%;
text-align: center;
}
img {
*position:relative;
*top:-50%;
}
實現絕對居中的另類方法
<style type="text/css">
.outer{
background:#9F6;
width:100%;
height:400px;
position:relative;
}
.inner{
width:50%;
height:50%;
background:#990;
margin:auto;
position:absolute;
left:0;
top:0;
right:0;
bottom:0;
}
</style>
<div class="outer">
<div class="inner">絕對居中</div>
</div>
兼容性:IE8+、firefox、chrome
注意:這里必須設置height屬性才能居中
