在 Web 開發中,經常遇到這樣的需求:一張寬高皆未知的圖片,必須在一個寬高固定的容器中實現垂直水平居中。雖然聽起來簡單,但因瀏覽器渲染差異,往往會出現 1-3 像素的偏移。本文整理了三種經典且兼容性良好的解決方案,供開發者參考。
外層容器尺寸固定(如 500×400px),內部圖片尺寸不定。目標是使圖片始終相對容器垂直居中。理想效果如下圖所示:

實際測試中,各瀏覽器解析差異導致微小偏移,需通過具體 Hack 處理。
利用 CSS 表格屬性:外層 display:table,內層 <span> 設為 display:table-cell; vertical-align:middle。現代瀏覽器完美支持,IE6/7 需單獨處理。
<div id="box">
<span><img src="images/demo.jpg" alt=""></span>
</div>
#box {
width: 500px; height: 400px;
display: table;
text-align: center;
border: 1px solid #d3d3d3; background: #fff;
}
#box span {
display: table-cell;
vertical-align: middle;
}
#box img { border: 1px solid #ccc; }
<!--[if lte IE 7]>
<style>
#box { position: relative; overflow: hidden; }
#box span { position: absolute; left: 50%; top: 50%; }
#box img { position: relative; left: -50%; top: -50%; }
</style>
<![endif]-->
優點:語義清晰,現代瀏覽器無 Hack;缺點:需額外 <span> 標籤。
原理相同,但用 * Hack 針對 IE6/7,省去條件註釋。
#box {
width: 500px; height: 400px;
overflow: hidden; position: relative;
display: table-cell; /* 標準瀏覽器生效 */
text-align: center; vertical-align: middle;
border: 1px solid #d3d3d3; background: #fff;
}
#box span {
position: static;
*position: absolute; *top: 50%; /* IE6/7 */
}
#box img {
position: static;
*position: relative; *top: -50%; *left: -50%; /* IE6/7 */
border: 1px solid #ccc;
}
缺陷:#box 設為 table-cell 導致無法使用 margin,且 IE8 下邊框失效。
標準瀏覽器同樣用 display:table-cell;IE 全系列通過插入 <i></i> 空標籤,設 height:100%; display:inline-block; vertical-align:middle 撐開高度,配合圖片 vertical-align:middle 實現居中。
<div id="box"><i></i><img src="images/demo.jpg" alt=""></div>
#box {
width: 500px; height: 400px;
display: table-cell;
text-align: center; vertical-align: middle;
border: 1px solid #d3d3d3; background: #fff;
}
#box img { border: 1px solid #ccc; }
<!--[if IE]>
<style>
#box i { display: inline-block; height: 100%; vertical-align: middle; }
#box img { vertical-align: middle; }
</style>
<![endif]-->
此法兼容性佳,限制較小,亦適用 Transitional 型文檔。
上述三法均源自藍色理想社區,經實測兼容性最佳。許多方案依賴 display:table 模擬表格行為,若 CSS 未來提供原生垂直居中屬性(如 Flexbox/Grid)將大幅簡化開發。若您有更優雅的方案,歡迎分享交流。