.container {
width: 960px; /* 必須有寬度 */
margin: 0 auto; /* 上下 0、左右自動 → 置中 */
}
IE6 需在 body 加 text-align:center,再於容器重設 text-align:left。
.wrap {
display: flex;
justify-content: center; /* 主軸置中 */
}
.child { /* 寬度由內容決定或自行設定 */ }
.wrap {
display: grid;
place-items: center; /* 水平垂直皆置中 */
/* 或僅水平:justify-items: center; */
}
.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:center | IE10+ (需 -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" 等已棄用屬性。