CSS margin collapsing
ID: css-margin-collapsing
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.[ref]
For two eligible sibling blocks, a first block's bottom margin of CSS pixels and the next block's top margin of give a collapsed margin of , not . Positive adjoining margins contribute their largest value.
Negative values make the rule more interesting. For a collapsing group with a positive margin of and a negative margin of , the result is pixels. With only and , it is , not . More generally, take the largest positive value, or zero if none, and subtract the largest absolute negative value, or zero if none.[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.[ref]
Box model in CSS 2.2 by W3C. §8.3.1, inline-block and block-formatting-context exclusions and parent-child cases
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.
New to topics? Read the docs here!