利用 inline-block 元素參考基線對齊特性,配合一個 **滿高度的幽靈元素** 作為對齊基準:
.img-box {
width: 100%;
height: 400px;
border: 1px solid red;
text-align: center; /* 水平置中 */
font-size: 0; /* 消除 inline-block 間隙 */
}
.img-box::before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
}
.img-box img {
display: inline-block;
vertical-align: middle;
max-width: 100%;
max-height: 100%;
}
<div class="img-box">
<img src="photo.jpg" alt="">
<i></i> <!-- 幽靈元素 -->
</div>
.img-box { width: 100%; height: 400px; border: 1px solid red; text-align: center; }
.img-box img, .img-box i { display: inline-block; vertical-align: middle; }
.img-box i { height: 100%; }
<i>)height: 100% 撐滿容器高度inline-block,共享同一行框vertical-align: middle 使兩者**垂直置中對齊**(基線向上 0.5ex)text-align: center 實現水平置中inline-block 僅對天生行內元素生效 → <img>、<i>、<span> 可用,<div> 需 display: inline; *zoom: 1; Hackfont-size: 0 消除字符間隙(IE6/7 也生效).img-box {
display: flex;
justify-content: center;
align-items: center;
height: 400px;
}
.img-box {
display: grid;
place-items: center;
height: 400px;
}
.img-box {
display: table-cell;
vertical-align: middle;
text-align: center;
height: 400px;
}
| 方案 | 相容性 | HTML 淨度 | 推薦場景 |
|---|---|---|---|
| 偽元素 + inline-block | IE8+ | 純淨 | 需支援 IE8-9 的現代專案 |
| 實體標籤 + inline-block | IE6+ | 污染 HTML | 極舊專案維護 |
| Flexbox / Grid | IE10+ / IE11+ | 純淨 | 現代專案首選 |
| Table-cell | IE8+ | 純淨 | 需支援 IE8-9 且不想用偽元素 |
垂直置中曾是 CSS 經典難題,inline-block + vertical-align: middle + 幽靈元素 是相容 IE6 的終極解法。現代專案請直接使用 Flexbox/Grid,代碼量減少 80%、語意明確、零副作用。理解經典技巧原理,是為了在受限環境下依然能交付優雅方案。