Skip to content

[css] collapsing margin 是什麼?

Published: at 08:40 AM (3 min read)

不常寫前端的工程師們,時常為了各種的 CSS 行為感到挫折(圖述)

其中一個大概就是 collapsing margin,明明說好的 css box model

margin 卻不講武德的變成右邊那樣

理想的 box model

實際上的 box model


Collapsing margin 規格定義

讓我們來看看 CSS3 對於 margin 的規格定義

NOTE: Adjoining margins in block layout can collapse. See CSS2§8.3.1 Collapsing Margins for details. Also, margins adjoining a fragmentation break are sometimes truncated. See CSS Fragmentation 3 § 5.2 Adjoining Margins at Breaks for details.

https://www.w3.org/TR/css-box-3/#margins

看起來關於 margin 會 collapse 相關的定義,要參照 CSS2 spec 標準

可以看到 Collapsed margin 相關的規範

In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin.

Adjoining vertical margins collapse, except:

  • Margins of the root element’s box do not collapse.
  • If the top and bottom margins of an element with clearance are adjoining, its margins collapse with the adjoining margins of following siblings but that resulting margin does not collapse with the bottom margin of the parent block.
  • Horizontal margins never collapse.

https://www.w3.org/TR/CSS2/box.html#collapsing-margins

截取一下以上這段關於 Collapsed margin 的重點:

  1. 不一定發生在同層的元素(sibling),也可能是 parent / child 的元素關係

  2. root element(html) 不會發生

  3. 有部分清除浮動(clear)的元素出現時

  4. 水平方向的 margin 不會發生

簡單看以上幾點可能不是非常清楚,接下來我們直接看看實際的例子哪些會導致 Collapsing margin :P

  1. 當 parent / child 元素的垂直 margin 重疊時 (元素 margin-top / margin-bottom 都會發生)
    需達成以下前提,才會發生 Collapsing margin

    • parent 本身沒有設定 padding-top / border-top
    • parent 與 child 之間沒有其他有內容的元素 (非空元素)
  1. 空元素時 (margin-top / margin-bottom 會發生 collapsing)

看到以上這些例子,相信你也應該更了解該如何處理 Collapsing margin 的情況,統整一下可能的解法

參考資料