Margin Collapse

*update* at the time when I wrote this article I couldn't find any reliable resource explaining the css margin collapse feature.  Fortunately, the world has changed.  Learn about margin collapse on the MDN.

Lately I've given this site a much needed redesign. The blog posts will probably remain as infrequent as ever. But for now, I though I'd share an issue that had me scratching my head for a few hours.

The markup for my site looks something like this (I haven't jumped on the HTML5 bandwagon yet):

<div id="navigation">
<!-- navigation -->
</div>
<div id="content">
<h1>Title</h1>
</div>

I wanted to jam the navigation div right up next to the content div, so I set the top margin of the content div to 0, and the bottom margin of the navigation div to 0. Unfortunately, this doesn't quite work. There is still a mysterious gap between the two divs.

So how can it be? It turns out the h1 tag is the problem. h tags (and also p tags), come with a top margin by default, to separate them from the previous section. Thanks to a somewhat obscure CSS feature called margin collapse, the margin from the h1 tag gets combined with the margin of the content div, which causes the gap.

One solution would be to remove the margin from the h1 tag. That doesn't feel right to me, so instead I used a small hack to "disable" margin collapse on the content div. By adding a single pixel of padding to the div, margin collapse can be prevented.

In conclusion, margin collapse can cause mysterious gaps between divs, and the solution is to add some padding. Judging from the number of unhelpful and misleading forum posts I came up with on Google, I'd say this is a common newbie problem.