Div 置中是 CSS 基礎必考題。本文整理水平置中、垂直置中、水平垂直同時置中的多種經典與現代寫法。
/* 父層 */
body { text-align: center; } /* IE 相容 */
/* 子層 */
#center { margin-left: auto; margin-right: auto; }
現代寫法:#center { margin: 0 auto; }(需指定寬度)。
body { background: url(img.jpg) no-repeat center; }
關鍵在 center 關鍵字,等同 50% 50%。
#center {
height: 200px; line-height: 200px; /* 行高等於容器高 */
vertical-align: middle; text-align: center;
}
原理:行內框高度等於 line-height,vertical-align:middle 使基線置中於行內框,單行文字即視覺置中。
.parent { display: flex; align-items: center; justify-content: center; height: 200px; }
.child { /* 任意寬高 */ }
Flexbox 一行解決水平垂直雙向置中,IE10+ 完整支援,為現代首選。
.parent { display: table-cell; vertical-align: middle; text-align: center; }
IE8+ 支援,無需固定高度即可垂直置中。
根據專案瀏覽器支援需求選擇適當方案,Flexbox 為首選、table-cell 為備援、line-height 單行專用。