萬盛學電腦網

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

CSS 垂直置中五大經典方案:table、absolute、margin:auto、Flexbox、Grid

方案一:display:table(IE8+)

.wrapper { display: table; width: 500px; height: 500px; }
.row { display: table-row; }
.cell { display: table-cell; vertical-align: middle; }

優點:不需知道內容高度。缺點:IE6/7 不支援,結構較繁瑣。

方案二:absolute + 負 margin(全瀏覽器)

.wrapper { position: relative; width: 500px; height: 500px; }
.content { position: absolute; top: 50%; left: 0; width: 400px; height: 300px; margin-top: -150px; }

優點:相容性最好。缺點:必須知道內容高度。

方案三:偽元素輔助(同方案二原理)

.wrap { height: 500px; }
.additional { height: 50%; margin-bottom: -120px; } /* 內容高度一半 */
#content { height: 240px; }

缺點:需額外標籤、同樣需知高度。

方案四:absolute + margin:auto(IE8+)

.content {
  position: absolute; top: 0; bottom: 0; left: 0; right: 0;
  margin: auto; width: 70%; height: 240px;
}

優點:程式碼極簡。缺點:IE6/7 不支援、需固定高寬。

方案五:單行文字 line-height

.single-line { height: 50px; line-height: 50px; }

僅適用單行文字。

現代最佳解:Flexbox / Grid(IE10+ / 全現代瀏覽器)

.wrapper { display: flex; align-items: center; justify-content: center; height: 500px; }
/* 或 */
.wrapper { display: grid; place-items: center; height: 500px; }
  • 不需知內容尺寸。
  • 同時解決水平+垂直置中。
  • 程式碼最少、維護最易。

選擇決策樹

  1. 支援 IE6/7 且內容固定高度 → 方案二。
  2. 支援 IE8+ 且內容固定高度 → 方案四。
  3. 不需支援舊 IE → Flexbox/Grid 首選。
  4. 單行文字 → `line-height`。
copyright © 萬盛學電腦網 all rights reserved