margin 是 CSS 最常用、最基礎、也最容易踩坑的屬性。你真的掌握它的所有特性嗎?垂直外邊距合併、BFC 隔離、負 margin 拉版、inline 元素的特殊行為……本文從規範到實戰,一次講透。
margin-top/right/bottom/leftlength | percentage | auto最佳實踐:避免使用 3 值寫法(margin: 10px 20px 30px),易讀性差且維護時極易出錯。寧可多打幾個字,也要寫完整 4 值。
相鄰塊級元素的上下 margin 合併為較大者;父子元素首尾 margin 穿透父容器(無 padding/border/block formatting context 時)。
<div class="parent">
<div class="child" style="margin-top: 20px">內容</div>
</div>
現象:.parent 上方出現 20px 空白,而非子元素內部凹陷。
overflow: hidden/autodisplay: flow-root(現代首選)float: left / position: absolute / display: flex/gridpadding-top: 1px 或 border-top: 1px solid transparent推薦 display: flow-root:語義清晰、無副作用、不觸發舊版 IE hasLayout Bug。
| 場景 | 選 Margin | 選 Padding |
|---|---|---|
| 元素間距 | ✅ 隔離模組,可合併 | ❌ |
| 內容與邊框間距 | ❌ | ✅ 保留背景色/圖 |
| 需要背景延伸至邊框 | ❌ | ✅ |
| 負值拉版/重疊 | ✅ 負 margin 神技 | ❌ Padding 不接受負值 |
| inline 元素 | 僅水平方向生效 | 四向生效但不影響行高 |
核心心法:Margin 隔離模組,Padding 呼吸內容。
inline-block。.col { padding-bottom: 9999px; margin-bottom: -9999px; }
.container { overflow: hidden; }
.modal { margin-top: -150px; /* 自身高度一半 */ margin-left: -200px; /* 寬度一半 */ }
.wrapper { line-height: 200px; }
.text { display: inline-block; vertical-align: middle; line-height: 1.5; }
display: inline 修復。margin: auto 在 flex/grid 容器中表現不同 → 明確指定對齊屬性。下次寫 margin 時,腦海裡浮現「氣墊、隔離艙、負壓」,你就真正懂了。