問題代碼
.ABC { width:100px; height:100px; background:red; margin:auto; margin-left:20px; }
/* 預期:置中再左移 20px,實際:左邊距 20px,不置中 */
根因:CSS 級聯覆蓋順序
margin:auto 展開為 margin-top:auto; margin-right:auto; margin-bottom:auto; margin-left:auto;。
- 後寫的
margin-left:20px **覆蓋** 了 margin-left:auto。
- 結果:
margin-left:20px; margin-right:auto; → 元素靠左 20px,右邊自動填滿剩餘空間,**不置中**。
解決方案對比
| 方法 | 代碼 | 原理 | 適用場景 |
| 相對定位 (推薦) | .ABC { margin:auto; position:relative; left:-20px; } | 不影響佈局流,視覺偏移,不改 margin 計算 | 微調、動畫、響應式安全 |
| 負外邊距 | .ABC { margin:auto; margin-left:calc(50% - 50px - 20px); margin-right:calc(50% + 50px + 20px); } | 利用 margin 計算強制置中偏移 | 不支援 calc 的舊瀏覽器不可用 |
| Flex 父容器 | .parent { display:flex; justify-content:center; } .ABC { transform:translateX(-20px); } | 現代佈局,transform 不觸發重排 | 新專案、需動畫 |
| 絕對定位 | .ABC { position:absolute; left:50%; margin-left:-70px; } | 傳統置中偏移技巧 | 脫離文檔流,父容器需 relative |
核心觀念
- margin:auto 置中 需要**左右 margin 同時為 auto**。任何一方被具體數值覆蓋即失效。
- 視覺偏移 (position:relative/transform) **不改變佈局幾何**,最安全。
- 避免同屬性多次宣告,改用
margin: 0 auto 單行寫法減少覆蓋風險。