垂直置中是 CSS 常見難題。本文介紹最相容、結構最簡潔的「絕對定位負邊距法」,適用已知固定高度的區塊。
position: relative(或任意非 static 定位)。position: absolute; top: 50%; 將頂邊對齊父容器垂直中心。margin-top: -自身高度一半,將子元素向上拉回真正置中。/* HTML */
置中內容
/* CSS */
.container { position: relative; height: 300px; }
.content {
position: absolute;
top: 50%;
height: 120px; /* 必須固定高度 */
margin-top: -60px; /* 負值為高度一半 */
width: 80%; /* 寬度可自適應 */
}
| 優點 | 缺點 |
|---|---|
| 相容所有瀏覽器(含 IE6+) | 需知固定高度,動態內容不適用 |
| 無需額外巢狀標籤 | 容器空間不足時內容會被截斷/消失(類似 body 內無滾動條) |
| 結構簡潔、易理解 |
display:flex; align-items:center; justify-content:center;)或 Grid 現代解法。display:table-cell; vertical-align:middle; 方案。掌握此經典解法,並了解其適用邊界,再根據專案瀏覽器支援需求選擇最佳置中策略。