給區塊元素設定寬度,左右外距設為 auto,瀏覽器會自動計算相等值,實現水平置中:
#content {
width: 700px; /* 必須有明確寬度 */
margin: 0 auto; /* 上下 0、左右 auto */
}
IE6 不支援區塊元素 margin: auto,但會錯誤地繼承 text-align: center 使區塊置中。需雙重設定:
body { text-align: center; } /* IE6 讓 #content 置中 */
#content {
text-align: left; /* 重置內容文字靠左 */
width: 700px;
margin: 0 auto; /* 標準瀏覽器生效 */
}
父層設為 Flex 容器,子元素自動置中,無需寬度:
.container { display: flex; justify-content: center; }
.child { /* 無需 width、margin */ }
.container { display: grid; place-items: center; }
/* 或 place-content: center 針對整個網格置中 */
.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; /* 負邊距 = 自身高/寬一半 */
}
.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-9 | Table Display 或 絕對定位+負邊距 | 避免 Flexbug |