CSS Margin Collapsing Quirk

Learning new CSS things (aka. quirks) each day – though sometimes in very frustrating ways =p

I was working on a design and was having an issue where my divs were flush-up against the parent section, despite the fact that I had defined a margin on my child div. Basically, my margin:top was not showing up at all! After doing some research, I found out that margins will collapse when they’re adjoining!

8.3.1 Collapsing margins

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.

Two margins are adjoining if and only if:

  • both belong to in-flow block-level boxes that participate in the same block formatting context
  • no line boxes, no clearance, no padding and no border separate them
  • both belong to vertically-adjacent box edges, i.e. form one of the following pairs: top margin of a box and top margin of its first in-flow child

The solution to force margins to not collapse into each other:

  • Floating either of the div elements
  • Making either of your div elements inline blocks
  • Setting overflow of the parent section to auto (or any value other than visible)

Duncan Leung

Front End Developer at iHerb.com

Irvine, CA

Subscribe to Duncan Leung: Javascript and Front End Development

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!