Margin Collapse is a foxy little fox that dresses like George Clooney in the Fantastic Mr Fox. It’s a sly one alright and has caused many a good web developer to bash their head in frustration when that pesky margin will just not disappear.
So what is margin collapse. Well usually it just happens and it passes unnoticed. Margin collapsing is where the browser will combine the margins of two elements and then only apply the larger of the two.
This can happen in a number of cases.
Firstly, when you have adjacent sibling elements ie
<p>My paragraph</p> <p>I am your sibling</p>
In this situation if the first
<p> has a margin-bottom of 50px and the second
<p> has a margin-top of 100px – then the margin will collapse – ie will be equal to the larger of the two values ie 100px.
See a demo here.
Generally this can pass without notice.
The other scenario is where there are parent / child elements ie
<body> <div>My content</div> </body>
In this scenario if the margin-top of parent is not separated from the margin-top of the child then the margins collapse. This can also happen with the parent / child margin-bottom properties.
Have a look at this demo file.
Notice how the yellow container does not fill out to the top of the page. Now you may think that maybe this is because you need to put 0 margins and padding on the
<body> and then the yellow of the container will fill to the top. Try it on the demo. Hmmm maybe not.
The margin-top of
<body> needs to be separated from the margin-top of the
<div> and can be done by adding a border, some padding or some inline content.
Return to the demo and click the button to apply padding to the top of the container and we now see the top margin removed.
Got yer you pesky foxy fox.