萬盛學電腦網

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

CSS 區塊元素水平置中完整指南 (margin:auto / Flex / Grid / Absolute)

經典方案:定寬 + margin:auto

.container {
  width: 960px;       /* 必須有寬度 */
  margin: 0 auto;     /* 上下 0、左右自動 → 置中 */
}

IE6 需在 body 加 text-align:center,再於容器重設 text-align:left。

現代方案:Flexbox (不需定寬)

.wrap {
  display: flex;
  justify-content: center; /* 主軸置中 */
}
.child { /* 寬度由內容決定或自行設定 */ }

Grid 方案

.wrap {
  display: grid;
  place-items: center; /* 水平垂直皆置中 */
  /* 或僅水平:justify-items: center; */
}

Absolute + Transform (未知寬高置中)

.parent { position:relative; }
.child {
  position:absolute; left:50%; top:50%;
  transform:translate(-50%, -50%);
}

對比表

方法需定寬垂直置中IE 支援適用場景
margin:auto是否IE6+ (需 text-align hack)固定寬版型、頁面主容器
Flex justify-content否align-items:centerIE10+ (需 -ms-)現代響應式佈局
Grid place-items否內建Edge 16+二維佈局、整頁置中
Absolute + Transform否是IE9+彈窗、Tooltip、浮動元素
Table margin:auto是否IE8+舊專案相容

最佳實務建議

  • **頁面主容器**:max-width:1200px; margin:0 auto; padding:0 1rem; (響應式、無水平捲動)。
  • **組件內部置中**:優先 display:flex; justify-content:center。
  • **彈窗/浮層**:position:fixed; inset:0; margin:auto (定寬高) 或 transform:translate(-50%,-50%) (不定寬高)。
  • 避免 <center>、align="center" 等已棄用屬性。
copyright © 萬盛學電腦網 all rights reserved