萬盛學電腦網

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

CSS 垂直置中五大方案:從 Table-Cell 到 Flex/Grid 現代最佳解

場景定義

父容器高度固定/可計算,子元素高度不定 (文字換行、圖片、動態內容),需垂直置中。

方案一:Table-Cell 模擬 (IE8+)

.vc-table { display: table; width: 500px; height: 500px; background: #c00; }
.vc-table__row { display: table-row; }
.vc-table__cell { display: table-cell; vertical-align: middle; text-align: center; }

/* HTML */
<div class="vc-table">
  <div class="vc-table__row">
    <div class="vc-table__cell">垂直置中內容</div>
  </div>
</div>

優點:語義接近表格、不需知子元素高度。
缺點:HTML 結構冗余、IE6-7 不支援、難以配合其他佈局。

方案二:絕對定位 + 負 Margin (IE6+)

.vc-abs { position: relative; width: 500px; height: 500px; background: #c00; }
.vc-abs__inner { 
  position: absolute; top: 50%; left: 0; right: 0;
  width: 400px; height: 300px; /* 必須知高度 */
  margin-top: -150px;          /* 高度一半取負 */
  background: pink; 
}

優點:兼容性極佳。
缺點:**必須知曉子元素確切高度**,不適合動態內容。

方案三:偽元素 + Inline-Block (IE7+)

.vc-ib { height: 500px; background: pink; text-align: center; *zoom:1; } /* IE7 hasLayout */
.vc-ib::before {
  content: ''; display: inline-block; height: 100%; vertical-align: middle;
}
.vc-ib__inner {
  display: inline-block; vertical-align: middle;
  width: 70%; background: #000; text-align: left;
}

原理:偽元素撐滿高度成基線,內層 inline-block 基線對齊。
優點:不需知子元素高度。
缺點:需額外偽元素、IE7 需 zoom:1、字體大小影響基線位置。

方案四:Absolute + Margin Auto (IE11+ / 現代)

.vc-margin {
  position: absolute; top: 0; right: 0; bottom: 0; left: 0;
  margin: auto;
  width: 70%; height: 240px; /* 需知寬高 */
  background: #000;
}

原理:四向定位 0 + 固定尺寸 + margin:auto 瀏覽器自動分配剩餘空間。
缺點:**需知寬高**、IE10- 不支援。

方案五:單行文字 Line-Height (極簡)

.vc-line { height: 100px; line-height: 100px; } /* 單行文字垂直置中 */

僅適用**單行文字**,多行失效。

現代最佳解:Flexbox / Grid (一行代碼)

/* Flexbox - IE10+ (需前綴) / 現代全支援 */
.vc-flex { display: flex; align-items: center; justify-content: center; min-height: 500px; }

/* Grid - 現代瀏覽器 */
.vc-grid { display: grid; place-items: center; min-height: 500px; }

方案對比總表

方案相容需知子高度代碼量多行文字推薦指數
Table-CellIE8+否中✅⭐⭐ (舊專案)
Abs + 負 MarginIE6+**是**少✅⭐ (固定尺寸)
偽元素 + Inline-BlockIE7+否中✅⭐⭐⭐ (IE7-10)
Abs + Margin AutoIE11+**是**極少✅⭐⭐ (固定尺寸)
Line-Height全否極少❌⭐ (單行專用)
FlexboxIE10+否**1 行**✅⭐⭐⭐⭐⭐ 首選
Grid現代否**1 行**✅⭐⭐⭐⭐⭐ 二維佈局首選

進階:容器高度也自適應 (頁面級置中)

html, body { height: 100%; }
.page-center { min-height: 100vh; display: flex; align-items: center; justify-content: center; }

圖片垂直置中特例

.img-vc { display: flex; align-items: center; justify-content: center; height: 300px; }
.img-vc img { max-width: 100%; max-height: 100%; object-fit: contain; }

總結

**新專案直接用 Flexbox/Grid**,代碼最少、維護最易、功能最強 (同時解決水平置中、多欄對齊、換行)。僅在維護 IE9- 專案時,選擇 **偽元素 + Inline-Block** 或 **Table-Cell**。理解各方案原理,能在受限環境下做最優選擇。

copyright © 萬盛學電腦網 all rights reserved