Collapsing margins

According to MDN,

Top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the margins combined into it, a behaviour known as margin collapsing.

Only vertical margins are collapsed.

The concept of margin collapsing comes from graphic design. There, you have margins to title and subtitles, but when a subtitle comes just after the title you should not double the margins. This is why they developed the concept of collapsed margins and this is why it happens just on vertical margins.

When margins were introduced to web design, websites were just white pages with formatted text in it. So, margins were used basically for text or images inside the text. Basically all elements were display:inline, so the collapsed margins were the way to go and became the norm.

Margin-collapsing are of 3 types:

Adjacent siblings:

  1. If both positive/negative, the smaller one is collapsed.
  2. If one negative and one positive, both are added.

Parent and first/last child

The smaller margin-top is collapsed if there is no separating

  1. border
  2. padding
  3. inline-content
  4. clearance (i.e. clear property on the child)

In this case, the parent’s top-margin prevails.

The smaller margin-bottom is collapsed if there is no separating

  1. border
  2. padding
  3. inline-content
  4. height or max-height or min-height

In this case, the parent’s bottom-margin prevails.

Empty blocks:

Top and bottom margins collapse if no separating

  1. border
  2. padding
  3. inline-content
  4. height or min-height.

More complex margin collapsing (of more than two margins) occurs when these cases are combined.

These rules apply even to margins that are zero, so the margin of a first/last child ends up outside its parent (according to the rules above) whether or not the parent’s margin is zero.

When negative margins are involved, the size of the collapsed margin is the sum of the largest positive margin and the smallest (most negative) negative margin.

Margin-collapsing does not apply on:

  • floated elements
  • absolutely positioned elements
  • inline-block elements
  • elements with overflow set to anything other than visible (They do not collapse margins with their children.)
  • cleared elements (They do not collapse their top margins with their parent block’s bottom margin.)
  • the root element