舊文常說:「margin: 0 auto 在 FF 置中,IE 不行,需在 body 加 text-align: center」。這是 IE5/6 Quirks Mode 行為。現代標準模式(<!DOCTYPE html>)下,所有瀏覽器均支援 margin: 0 auto 置中區塊元素。
| 方法 | 適用元素 | 需知寬度 | 瀏覽器支援 | 優點 | 缺點 |
|---|---|---|---|---|---|
margin: 0 auto |
Block-level (div, p, section...) | 是 | IE6+ (標準模式) | 語意純粹、無副作用、效能最佳 | 需明確 width/max-width |
| Flexbox | Flex Container 子元素 | 否 | IE10+ | 支援多欄、垂直置中、自動換行 | 需父層 display:flex |
| Grid | Grid Container 子元素 | 否 | IE10+ (前綴) | 二維對齊、place-items:center 一行搞定 | 較重、IE 需前綴 |
| Transform | Absolute/Fixed 定位元素 | 否 | IE10+ | 不需寬高、可動畫 | 可能模糊、建立堆疊上下文 |
.container {
max-width: 1200px;
margin: 0 auto; /* 水平置中 */
}
.flex-center {
display: flex;
justify-content: center; /* 主軸置中 → 水平 */
/* align-items: center; 交叉軸置中 → 垂直 */
}
.grid-center {
display: grid;
place-items: center; /* 水平 + 垂直同時置中 */
}
.modal {
position: fixed;
top: 50%; left: 50%;
transform: translate(-50%, -50%);
/* 無需寬高,自適應內容 */
}
width: auto 撐滿容器,margin:auto 無效果。必須給 width、max-width 或 fit-content。display:inline-block 或 float 且無寬度,子元素無法置中。修正父容器佈局。justify-content,導致意外行為。避免混用。transform 會建立新的 containing block,position:fixed 子元素將相對最近的 transform 祖先定位,而非 viewport。解法:將 fixed 元素移出 transform 層級。margin: 0 auto + max-width。不再為置中煩惱,根據元素類型與佈局上下文選對工具,一次到位。更多 CSS 佈局核心技巧,請持續關注本站系列。