父容器高度固定/可計算,子元素高度不定 (文字換行、圖片、動態內容),需垂直置中。
.vc-table { display: table; width: 500px; height: 500px; background: #c00; }
.vc-table__row { display: table-row; }
.vc-table__cell { display: table-cell; vertical-align: middle; text-align: center; }
/* HTML */
<div class="vc-table">
<div class="vc-table__row">
<div class="vc-table__cell">垂直置中內容</div>
</div>
</div>
優點:語義接近表格、不需知子元素高度。
缺點:HTML 結構冗余、IE6-7 不支援、難以配合其他佈局。
.vc-abs { position: relative; width: 500px; height: 500px; background: #c00; }
.vc-abs__inner {
position: absolute; top: 50%; left: 0; right: 0;
width: 400px; height: 300px; /* 必須知高度 */
margin-top: -150px; /* 高度一半取負 */
background: pink;
}
優點:兼容性極佳。
缺點:**必須知曉子元素確切高度**,不適合動態內容。
.vc-ib { height: 500px; background: pink; text-align: center; *zoom:1; } /* IE7 hasLayout */
.vc-ib::before {
content: ''; display: inline-block; height: 100%; vertical-align: middle;
}
.vc-ib__inner {
display: inline-block; vertical-align: middle;
width: 70%; background: #000; text-align: left;
}
原理:偽元素撐滿高度成基線,內層 inline-block 基線對齊。
優點:不需知子元素高度。
缺點:需額外偽元素、IE7 需 zoom:1、字體大小影響基線位置。
.vc-margin {
position: absolute; top: 0; right: 0; bottom: 0; left: 0;
margin: auto;
width: 70%; height: 240px; /* 需知寬高 */
background: #000;
}
原理:四向定位 0 + 固定尺寸 + margin:auto 瀏覽器自動分配剩餘空間。
缺點:**需知寬高**、IE10- 不支援。
.vc-line { height: 100px; line-height: 100px; } /* 單行文字垂直置中 */
僅適用**單行文字**,多行失效。
/* Flexbox - IE10+ (需前綴) / 現代全支援 */
.vc-flex { display: flex; align-items: center; justify-content: center; min-height: 500px; }
/* Grid - 現代瀏覽器 */
.vc-grid { display: grid; place-items: center; min-height: 500px; }
| 方案 | 相容 | 需知子高度 | 代碼量 | 多行文字 | 推薦指數 |
|---|---|---|---|---|---|
| Table-Cell | IE8+ | 否 | 中 | ✅ | ⭐⭐ (舊專案) |
| Abs + 負 Margin | IE6+ | **是** | 少 | ✅ | ⭐ (固定尺寸) |
| 偽元素 + Inline-Block | IE7+ | 否 | 中 | ✅ | ⭐⭐⭐ (IE7-10) |
| Abs + Margin Auto | IE11+ | **是** | 極少 | ✅ | ⭐⭐ (固定尺寸) |
| Line-Height | 全 | 否 | 極少 | ❌ | ⭐ (單行專用) |
| Flexbox | IE10+ | 否 | **1 行** | ✅ | ⭐⭐⭐⭐⭐ 首選 |
| Grid | 現代 | 否 | **1 行** | ✅ | ⭐⭐⭐⭐⭐ 二維佈局首選 |
html, body { height: 100%; }
.page-center { min-height: 100vh; display: flex; align-items: center; justify-content: center; }
.img-vc { display: flex; align-items: center; justify-content: center; height: 300px; }
.img-vc img { max-width: 100%; max-height: 100%; object-fit: contain; }
**新專案直接用 Flexbox/Grid**,代碼最少、維護最易、功能最強 (同時解決水平置中、多欄對齊、換行)。僅在維護 IE9- 專案時,選擇 **偽元素 + Inline-Block** 或 **Table-Cell**。理解各方案原理,能在受限環境下做最優選擇。