# margin collapsing

{% hint style="danger" %}
**Margin collapsing** only occurs with **top** and **bottom** margins, **left** and **right** margins **don’t collapse**.
{% endhint %}

`margin` 有個重要的特性，叫做「**邊距重疊**」([margin collapsing](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing))，意思是兩個或多個元素 (父子、兄弟) 的「**垂直邊距**」會自動組合成**單個邊距**。重疊邊距採用**最大的 margin 值**，此外如果元素本身**高度**為 **0** 或 **auto**，則會發生上下 margin 重疊狀況。 :point\_right: [Margin Collapsing](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing)

{% hint style="info" %}
不過在下列的情形中，元素**不會**發生邊距重疊：

* **父元素**有設定 **padding** 或 **border** 的寬度。
* margin collapsing **does not work** on **margin-left** and **-right**, just on -top and -bottom.
* 屬於「不同的 [BFC](https://lochiwei.gitbook.io/web/css/layout/block-formatting-context) 內」的元素，例如：
  * position 使用 absolute、fixed 的元素。
  * 元素間穿插了 [BFC](https://lochiwei.gitbook.io/web/css/layout/block-formatting-context) 元素，例如 inline、table...等。
  * display 屬性為 inline-block、table-cell、table-caption 的元素。
  * display 屬性為 flex、inline-flex、grid、inline-grid 的元素。
    {% endhint %}

## preventing margins from collapsing <a href="#prevent-collapsing" id="prevent-collapsing"></a>

* the margins of **flexbox items** **don’t collapse**.
* if you add **top** and **bottom** **padding/border** to the **parent** container, the **margins inside it won’t collapse** to the outside.
* applying **overflow: auto** (or any value other than **visible**) to the **container** prevents margins inside the container from collapsing with those outside the container.
* elements with **display: table-cell** don’t have a margin, so they won’t collapse, this also applies to **table-row** and **most other table display** types. \
  (exceptions: **table**, **table-inline**, and **table-caption**)

## margins between elements

```css
/* 
    use adjacent sibling combinator (+) 
    to apply a margin between buttons 
*/
.button + .button {
    margin-block-start: 0.5em;
}
```

## 參考 <a href="#ref" id="ref"></a>

* [深入理解 CSS Box Model](https://www.oxxostudio.tw/articles/202008/css-box-model.html)
* [Margin Collapsing](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing)
