What is the point of CSS collapsing margins?

Tom picture Tom · Jun 18, 2010 · Viewed 7k times · Source

The CSS2 box model tells us that adjoining vertical margins collapse.

I find it quite annoying, being the source of many design bugs. I hope that by understanding the purpose of collapsing margins, I will understand when to use them and how to avoid them when they are not needed.

What is the purpose of this feature?

Answer

VoteyDisciple picture VoteyDisciple · Jun 18, 2010

The general meaning of "margin" isn't to convey "move this over by 10px" but rather, "there must be 10px of empty space beside this element."

I've always found this is easiest to conceptualize with paragraphs.

If you just gave paragraphs margin-top: 10px and had no margins on any other elements, a series of paragraphs would be spaced beautifully. But of course, you'd run into trouble when placing another element underneath a paragraph. The two would touch.

If margins didn't collapse, you'd hesitate to add margin-bottom: 10px to your previous code, because then any pair of paragraphs would get spaced 20px apart, while paragraphs would separate from other elements by only 10px.

So vertical margins collapse. By adding top and bottom margins of 10px you're saying, "I don't care what margin rules any other elements have. I demand at least 10px of padding above and below each of my paragraphs."