CSS 中「垂直置中」歷來是經典難題。隨著 Flexbox、Grid 普及,現已有多種標準解法,可根據瀏覽器支援需求與佈局情境選擇。
| 方案 | 適用場景 | IE 支援 | 優點 | 缺點 |
|---|---|---|---|---|
| Flexbox | 現代專案首選 | IE10+ (部分前綴) | 語意清晰、支援多行、響應式友善 | 舊瀏覽器需前綴 |
| CSS Grid | 二維佈局、重疊元素 | IE10+ (舊語法) | 極簡代碼、強大對齊控制 | IE 需 autoprefixer |
| Table/Table-cell | 需支援 IE8+ | IE8+ | 相容性好、垂直置中天然支援 | 語意不純、佈局受限 |
| Absolute + Transform | 固定尺寸元素、彈窗 | IE9+ | 不需父層配合、動畫友善 | 需知寬高或用 transform |
| Line-height | 單行文字、固定高度 | 全瀏覽器 | 極簡 | 多行失效、高度不可變 |
.center-flex {
display: flex;
justify-content: center; /* 水平 */
align-items: center; /* 垂直 */
min-height: 200px; /* 需有高度 */
}
多行文字自動換行置中,無額外限制。
.center-grid {
display: grid;
place-items: center; /* 等同 align-items + justify-items */
min-height: 200px;
}
.center-table {
display: table-cell;
vertical-align: middle;
text-align: center;
width: 400px; height: 200px;
}
/* 外層需 display: table 或實際 table 元素 */
.center-absolute {
position: absolute;
top: 50%; left: 50%;
transform: translate(-50%, -50%);
/* 不需知道寬高 */
}
⚠️ 父層需 position: relative。
⚠️ Transform 會建立新的堆疊上下文,影響 z-index。
.center-line {
height: 48px;
line-height: 48px;
text-align: center;
white-space: nowrap; /* 防換行破壞 */
}
vertical-align: middle 僅對 inline/inline-block/table-cell 生效line-height 會導致行距過大,改用 Flex/Gridmax-width/height、overflow: auto掌握置中後,建議學習 CSS clear:both 清除浮動原理與現代替代方案,理解浮動佈局收尾技巧。