| 方案 | 核心 CSS | 支援度 | 優點 | 缺點 |
|---|---|---|---|---|
| Table-Cell | display:table-cell; vertical-align:middle | IE8+ | 簡單、無額外標籤 | IE 需 Hack、無法配合 float/position |
| Flexbox | display:flex; align-items:center; justify-content:center | IE10+ | 功能最全、支援換行、響應式 | 舊瀏覽器需前綴 |
| Grid | display:grid; place-items:center | IE10+ (部分) | 最簡潔、二維置中 | IE 不支援 place-items |
| Absolute + Transform | position:absolute; top:50%; left:50%; transform:translate(-50%,-50%) | IE9+ | 不依賴父層 display、適用任何場景 | 需父層 relative、可能模糊(sub-pixel) |
| Line-height(單行文字/圖片) | line-height: containerHeight | 全瀏覽器 | 極簡 | 僅限單行、高度固定 |
.box {
display: table-cell;
vertical-align: middle;
text-align: center;
width: 200px; height: 200px;
border: 1px solid #eee;
/* IE Hack */
*display: block;
*font-size: 175px; /* ≈ 0.873 × height */
*font-family: Arial; /* 避免編碼導致 Hack 失效 */
}
.box img { vertical-align: middle; }
.container {
display: flex;
align-items: center;
justify-content: center;
min-height: 200px; /* 或 100vh */
}
img { max-width: 100%; max-height: 100%; }
若需支援 IE10-11,加 autoprefixer 自動補 -ms-flex-align 等前綴。