方案選擇取決於:**容器高度是否固定**、**子元素高度是否已知**、**是否需支援 IE**。
| 方案 | 適用場景 | 核心代碼 | 瀏覽器支援 | 優點 | 缺點 |
|---|---|---|---|---|---|
| Flex (推薦首選) | 任意高度、多行、未知尺寸 | .parent { display: flex; align-items: center; justify-content: center; } | IE10+ (需前綴) | 語義清晰、雙向居中、響應式友好、無副作用 | 極舊瀏覽器需降級 |
| Grid | 任意高度、二維佈局兼顧 | .parent { display: grid; place-items: center; } | 現代瀏覽器 | 代碼最少、place-items 一鍵雙向 | IE 不支援、Grid 過殺雞 |
| Absolute + Transform | 固定/未知高度、需脫流定位 | .parent { position: relative; } .child { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } | IE9+ | 兼容性好、脫流不影響兄弟 | 需父級相對定位、transform 創建層疊上下文 |
| Table-Cell | 固定高度容器、老專案維護 | .parent { display: table; } .child { display: table-cell; vertical-align: middle; } | IE8+ | 語義相對清晰、垂直居中穩定 | 會產生匿名表格盒、寬度計算特殊、難響應式 |
| Line-Height (單行文本專用) | 單行文字、固定高度容器 | .parent { height: 40px; line-height: 40px; } | 全瀏覽器 | 代碼極少、無額外 DOM | **多行失效**、高度變動需同步修改 |
.v-center { display: flex; align-items: center; } 類,漸進增強。
.tag-cloud {
display: flex;
flex-wrap: wrap;
align-content: center; /* 關鍵:交叉軸多行居中 */
justify-content: center;
min-height: 200px;
}
vertical-align: middle **僅對 inline/inline-block/table-cell 生效**,對 block/flex/grid 無效。margin: auto 在 **Flex/Grid 容器** 中可實現雙向居中,但在 Absolute 需配合 inset: 0。min-height 而無內容,居中仍生效;內容超出時正常換行。**Flex 是垂直居中的「萬金油」**,現代專案無腦首選。Grid 適合二維佈局順手一用。Absolute+Transform 解決脫流定位場景。Line-height 僅限單行文本。Table-Cell 留給老專案維護。選對工具,垂直居中不再是面試題,而是基本功。