萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS 垂直居中 5 大現代方案:Flex、Grid、Absolute+Transform、Table-Cell、Line-Height 完整對比

場景分類:單行文本 vs 多行/未知高度區塊

方案選擇取決於:**容器高度是否固定**、**子元素高度是否已知**、**是否需支援 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**多行失效**、高度變動需同步修改

現代最佳實踐決策樹

  1. 一般區塊/卡片/模態框內容 → **Flex** (或 Grid)
  2. 2. 單行按鈕/標籤/導航項 → **Line-Height** (若高度固定) 或 **Flex** (高度流體) 3. 需脫流定位的浮層/Tooltip → **Absolute + Transform** 4. IE8-9 必須支援且無法引入 Polyfill → **Table-Cell** 或 **Absolute + Transform** 5. 舊專案維護:局部引入 .v-center { display: flex; align-items: center; } 類,漸進增強。

進階:Flex 多行垂直居中 (彈性換行)

.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。
  • Flex 容器若有 min-height 而無內容,居中仍生效;內容超出時正常換行。

總結

**Flex 是垂直居中的「萬金油」**,現代專案無腦首選。Grid 適合二維佈局順手一用。Absolute+Transform 解決脫流定位場景。Line-height 僅限單行文本。Table-Cell 留給老專案維護。選對工具,垂直居中不再是面試題,而是基本功。

copyright © 萬盛學電腦網 all rights reserved