行內/行內區塊元素
.parent { text-align: center; }
.child { display: inline-block; /* 或 inline, inline-flex */ }
區塊元素(固定寬度)
.child { width: 600px; margin: 0 auto; }
區塊元素(不定寬度) - 傳統技巧
/* 方法 1: 相對定位 50% + -50% */
.parent { float: left; position: relative; left: 50%; }
.child { float: left; position: relative; left: -50%; }
/* 方法 2: table 包裝 */
.parent { display: table; margin: 0 auto; }
現代標準:Flexbox(推薦)
.parent { display: flex; justify-content: center; }
Grid 置中
.parent { display: grid; place-items: center; }
選擇建議
- 單一行內元素 → `text-align:center`。
- 固定寬度區塊 → `margin:0 auto`。
- 不定寬度、多元素、需垂直置中 → `flex` 或 `grid`。
- 舊專案維護 → 視相容需求選擇傳統技巧。