讓區塊在視窗或父容器正中央顯示,是彈窗、載入動畫、登入框的標準需求。本文對比三種主流方案,說明適用場景與優缺點。
#pageMain {
width: 1002px; height: 602px;
position: absolute; top: 50%; left: 50%;
margin: -301px 0 0 -501px; /* 負一半寬高 */
background: #0e4980;
}
/* 父容器需 position: relative 或 body 為定位基準 */
body { position: relative; min-height: 100vh; }
缺點:必須知道確切寬高,內容動態變化時需 JS 計算。
.center-box {
position: absolute; top: 50%; left: 50%;
transform: translate(-50%, -50%);
}
最通用的傳統方案,支援動態尺寸內容。
.parent {
display: flex;
justify-content: center; /* 水平 */
align-items: center; /* 垂直 */
min-height: 100vh; /* 佔滿視窗高 */
}
.child { /* 無需額外樣式 */ }
.parent {
display: grid;
place-items: center; /* 同時水平垂直置中 */
min-height: 100vh;
}
.parent { display: table; width: 100%; height: 100vh; }
.child { display: table-cell; vertical-align: middle; text-align: center; }
.child-inner { display: inline-block; /* 內容區塊 */ }
| 方案 | 需知寬高 | 相容性 | 代碼量 | 靈活度 | 推薦場景 |
|---|---|---|---|---|---|
| 負 Margin | 是 | IE8+ | 中 | 低 | 固定尺寸彈窗、舊專案維護 |
| Transform | 否 | IE10+ | 少 | 高 | 動態尺寸、相容 IE10+ |
| Flex | 否 | IE10+ | 少 | 高 | 現代專案首選 |
| Grid | 否 | 現代瀏覽器 | 極少 | 最高 | 新專案、複雜對齊 |
| Table | 否 | IE8+ | 中 | 中 | 極舊環境相容 |
<div class="modal-overlay">
<div class="modal-box">
<h2>登入</h2>
<form>...</form>
</div>
</div>
新專案首選 Grid place-items: center,代碼最少、語義最清晰、支援巢狀置中。需相容 IE10 時用 Flex。動態尺寸彈窗避免使用負 margin 方案。記住:父容器需有高度(如 min-height: 100vh)置中才生效。