「如何讓 div 層中的內容垂直居中」是流傳很廣的一道面試題。本文彙集了官方解法與幾種網友解法,橫向對比它們的思路與取捨。
<style type="text/css">
.box {
display: table-cell;
vertical-align: middle;
width: 200px;
height: 200px;
text-align: center;
/* hack for IE */
*display: block;
*font-size: 175px;
/* end */
border: 1px solid #eee;
}
.box img { vertical-align: middle; }
</style>
<div class="box">
<img src="test.jpg" />
</div>
核心是用 table-cell 讓容器具備表格單元格的垂直對齊能力,再用 IE 專用的星號 hack 讓舊版 IE 透過 font-size 撐出行高來模擬居中。
.box {
display: table-cell;
vertical-align: middle;
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
border: 1px solid #eee;
}
.box img { vertical-align: middle; }
讓 line-height 等於容器高度,適合內容為單行或圖片的場景。
.box {
text-align: center;
width: 200px;
height: 200px;
border: 1px solid #ff0;
vertical-align: middle;
display: table-cell;
}
.box img { margin-top: expression(100 - this.height/2); }
透過 IE 的 expression 動態計算 margin 來補償居中,兼容性依賴 IE,較不通用。
三種方法各有側重:淘寶解法兼顧標準與 IE hack、通用性最好;line-height 法最簡潔但侷限於單行;expression 法依賴 IE 私有特性。面試時能說出多種方案並分析取捨,才是真正展現功力的地方。