使用margin-top該注意的坑

2019-04-22
1 minutes read

問題

最近在切網頁版面的時候,突然很常遇到div無法正確對本身parent元素對齊的狀況,到StackOverFlow上面查了一下,發現這個問題叫做Collapsing margins

問題發生原因

引用MDN上的說明

Adjacent siblings The margins of adjacent siblings are collapsed (except when the latter sibling needs to be cleared past floats). Parent and first/last child If there is no border, padding, inline part, block formatting context created, or clearance to separate the margin-top of a block from the margin-top of its first child block; or no border, padding, inline content, height, min-height, or max-height to separate the margin-bottom of a block from the margin-bottom of its last child, then those margins collapse. The collapsed margin ends up outside the parent. Empty blocks If there is no border, padding, inline content, height, or min-height to separate a block’s margin-top from its margin-bottom, then its top and bottom margins collapse.

簡單來說就是

  1. 父元素與子元素都是block,且子元素沒有float屬性
  2. 父元素沒有border、padding、overflow屬性將內外隔開,以至於margin-top和margin-bottom重疊

解決方法

1. 子元素加上float屬性

See the Pen margin collapse solution4 by Kai-Lun Huang (@kaibaooo) on CodePen.

2. 子元素更改為inline-block

See the Pen margin collapse solution3 by Kai-Lun Huang (@kaibaooo) on CodePen.

3. 父元素加上border

See the Pen margin collapse solution2 by Kai-Lun Huang (@kaibaooo) on CodePen.

4. 父元素加上padding

See the Pen margin collapse solution1 by Kai-Lun Huang (@kaibaooo) on CodePen.

參考資料

MDN - Mastering margin collapsing

comments powered by Disqus

相關文章