萬盛學電腦網

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

CSS 區塊元素水平置中完整指南:現代與相容寫法

標準模式:margin: 0 auto

給區塊元素設定寬度,左右外距設為 auto,瀏覽器會自動計算相等值,實現水平置中:

#content {
  width: 700px;      /* 必須有明確寬度 */
  margin: 0 auto;    /* 上下 0、左右 auto */
}

IE6 及以下相容寫法

IE6 不支援區塊元素 margin: auto,但會錯誤地繼承 text-align: center 使區塊置中。需雙重設定:

body { text-align: center; }           /* IE6 讓 #content 置中 */
#content {
  text-align: left;                    /* 重置內容文字靠左 */
  width: 700px;
  margin: 0 auto;                      /* 標準瀏覽器生效 */
}

現代 Flexbox 置中(推薦)

父層設為 Flex 容器,子元素自動置中,無需寬度:

.container { display: flex; justify-content: center; }
.child { /* 無需 width、margin */ }

Grid 置中

.container { display: grid; place-items: center; }
/* 或 place-content: center 針對整個網格置中 */

Table Display 相容方案(IE8+)

.container { display: table; margin: 0 auto; }
.child { display: table-cell; vertical-align: middle; } /* 同時垂直置中 */

絕對定位置中(已知/未知寬度)

已知寬高

.parent { position: relative; }
.child {
  position: absolute;
  top: 50%; left: 50%;
  width: 400px; height: 300px;
  margin: -150px 0 0 -200px; /* 負邊距 = 自身高/寬一半 */
}

未知寬高(Transform 解法,IE9+)

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

選擇指南

場景推薦方法備註
頁面主容器置中margin: 0 auto + max-width搭配 RWD 最佳
元件內部子元素置中Flexbox justify-content: center彈性、無需寬度
模態框、彈窗絕對置中transform: translate(-50%, -50%)支援未知尺寸
需支援 IE8-9Table Display 或 絕對定位+負邊距避免 Flexbug

延伸閱讀

copyright © 萬盛學電腦網 all rights reserved