萬盛學電腦網

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

CSS 實現 DIV 水平垂直雙向置中:絕對定位、Flex、Grid 三大方案對比

前言

讓區塊在視窗或父容器正中央顯示,是彈窗、載入動畫、登入框的標準需求。本文對比三種主流方案,說明適用場景與優缺點。

方案一:絕對定位 + 負 Margin(需定寬高,IE8+)

#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 計算。

方案二:絕對定位 + Transform(不需知寬高,IE10+)

.center-box {
  position: absolute; top: 50%; left: 50%;
  transform: translate(-50%, -50%);
}

最通用的傳統方案,支援動態尺寸內容。

方案三:Flex 置中(現代標準,IE10+)

.parent {
  display: flex;
  justify-content: center; /* 水平 */
  align-items: center;     /* 垂直 */
  min-height: 100vh;       /* 佔滿視窗高 */
}
.child { /* 無需額外樣式 */ }

方案四:Grid 置中(最簡潔,現代瀏覽器)

.parent {
  display: grid;
  place-items: center;     /* 同時水平垂直置中 */
  min-height: 100vh;
}

方案五:表格佈局相容舊瀏覽器(IE8+)

.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)置中才生效。

copyright © 萬盛學電腦網 all rights reserved