CSS margin collapsing (source code)

= CSS margin collapsing
{c}

<CSS margin collapsing> combines eligible adjoining vertical margins into one collapsed margin. In the horizontal text layout described by CSS 2.2, this can occur between ordinary in-flow block boxes and in specified parent-child or empty-block situations. It does not mean that every pair of nearby margins is added or collapsed.<Box model in CSS 2.2 by W3C>[§8.3.1, adjoining-margin conditions]{ref}

For two eligible sibling blocks, a first block's bottom margin of $20$ <CSS pixels> and the next block's top margin of $30$ give a collapsed margin of $30$, not $50$. Positive adjoining margins contribute their largest value.

Negative values make the rule more interesting. For a collapsing group with a positive margin of $30$ and a negative margin of $-12$, the result is $30-12=18$ pixels. With only $-8$ and $-12$, it is $-12$, not $-20$. More generally, take the largest positive value, or zero if none, and subtract the largest absolute negative value, or zero if none.<Box model in CSS 2.2 by W3C>[§8.3.1, calculation with negative adjoining margins]{ref}

Eligibility comes before arithmetic. Horizontal margins do not collapse under these rules, and margins of a <CSS inline-block box> do not collapse with surrounding boxes or its in-flow children. A parent's top border or padding can prevent the top parent-child collapse that would otherwise occur. Establishing a separate <CSS block formatting context> also changes the relevant parent-child relationships.<Box model in CSS 2.2 by W3C>[§8.3.1, inline-block and block-formatting-context exclusions and parent-child cases]{ref}

A useful debugging example is a parent's first child's top margin apparently moving the whole group rather than creating an internal gap. Inspect whether those margins are adjoining before changing unrelated dimensions. The <CSS margin box> describes a box's margin geometry, while <CSS margin collapsing> specifies how eligible margins interact during layout.