容器高度固定/自適應,子元素高度不固定(文字換行、圖片載入、動態內容),需實現子元素垂直置中。
.v-center {
display: table-cell;
vertical-align: middle;
/* IE6-7 Hack */
*position: relative;
*top: 50%;
}
.v-center__inner {
display: block;
margin: 0 auto;
text-align: center;
/* IE6-7 Hack */
*position: relative;
*top: -50%;
}
HTML:
<div class="v-center">
<div class="v-center__inner">不定高度內容</div>
</div>
原理:外層模擬 <td> 利用 vertical-align: middle;內層配合相對定位抵消 50% 位移。IE6-7 不支援 display: table-cell,故用 Hack 模擬。
.v-center {
text-align: center;
height: 400px; /* 容器需有高度 */
/* IE7- 偽元素觸發 hasLayout */
*zoom: 1;
}
.v-center::before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
}
.v-center__inner {
display: inline-block;
vertical-align: middle;
width: 80%; /* 或自適應 */
text-align: left; /* 重置文字對齊 */
}
原理:偽元素撐滿容器高度,成為基線參考;內層 inline-block 與之基線對齊即達垂直置中。IE7 需在容器觸發 hasLayout(如 zoom:1)。
Flexbox 一行解決:
.v-center {
display: flex;
align-items: center; /* 垂直置中 */
justify-content: center; /* 水平置中(可選) */
min-height: 400px;
}
Grid 更簡潔:
.v-center {
display: grid;
place-items: center; /* 同時垂直+水平置中 */
min-height: 400px;
}
| 方案 | 相容性 | 代碼量 | 靈活度 | 適用場景 |
|---|---|---|---|---|
| Table-Cell | IE8+ | 中 | 中 | 需支援 IE8-9 的舊專案 |
| Inline-Block | IE7+ | 中 | 高 | 需支援 IE7、多行文字/圖片混排 |
| Flexbox | IE10+ | 極少 | 極高 | 現代專案首選,支援多軸對齊、換行 |
| Grid | 現代瀏覽器 | 最少 | 極高 | 二維佈局、卡片對齊、隱式軌道 |
若容器無固定高度,需配合 min-height: 100vh 或父層 Flex/Grid 鏈路:
/* 頁面級垂直置中 */
html, body { height: 100%; }
.page-center {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.img-center {
display: flex;
align-items: center;
justify-content: center;
height: 300px;
background: #f0f0f0;
}
.img-center img {
max-width: 100%;
max-height: 100%;
object-fit: contain; /* 保持比例完整顯示 */
}
新專案請直接使用 Flexbox 或 Grid,代碼最少、維護性最好、功能最強。僅在必須支援 IE9 以下時,才考慮 Table-Cell 或 Inline-Block 方案,並建議封裝為工具類 .v-center 統一管理。