Margin collapsing is something I’ve never really been aware of. I’m certain that I’ve come up against it, probably more than once, but not known what’s going on. I’ve probably just kept tweaking the CSS again and again until it worked.
But that’s all changing now. Here’s what margin collapsing is all about.
What is Margin Collapsing?
Margin collapsing is when the margins of two elements meet and one is disregarded in favour of the other. For example, say Element A has a
margin-bottom of 20 pixels and Element B has a
margin-top of 30 pixels; you would expect the total margin space between them to be 50 pixels. Well, it isn’t. It’s 30 pixels.
This is just one case where margin collapsing takes place. Let me explain each case.
Case 1. Adjacent Siblings
In this case, when there are two adjacent siblings (i.e. two
p elements within a parent
div) which have meeting/overlapping margins, it’s the largest margin that is shown.
In the example below, we would logically expect the margin between Element A and Element B to be 50 pixels. Instead, it’s 30 pixels.
Element A – Bottom Margin of 20px
Element B – Top Margin of 30px (this one ‘wins’)
Case 2. Parent & Child
This one’s a little more complex. Here’s the explanation from MDN:
If there is no border, padding, inline part, block formatting context created, or clearance to separate the“Master margin collapsing”, MDN Web Docs
margin-topof a block from the
margin-topof one or more of its descendant blocks; or no border, padding, inline content,
min-heightto separate the
margin-bottomof a block from the
margin-bottomof one or more of its descendant blocks, then those margins collapse. The collapsed margin ends up outside the parent.
In essence, what this means is that if a parent container element has a top or bottom margin and the first / the last / the only child has a corresponding top or bottom margin (with nothing in between, such as
padding), then the margins will collapse.
In the example below, we have bottom margins applied to the parent and child elements totalling 100 pixels, however only the parent’s 60 pixel bottom margin applies.
This is the parent with 60px bottom margin
This is the child with 40px bottom margin
It’s worth noting that the margins wouldn’t collapse if you applied
padding to the parent element.
Case 3. Empty Block
The final case is if you have an empty block and apply both a top and bottom margin to it. An empty block is essentially an element without any
padding, content or
In the example below, we have an empty
div element (hence you can’t see anything inside the black box) with a top margin of 80 pixels and a bottom margin of 60 pixels. Only the 80 pixel margin is applied to the element.