views:

129

answers:

2

The CSS2 box model tells us that adjoining 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?

A: 

It is supposed to be a nice way to space things.

Say i have a list of divs, with top and bottom margin equal to 5px. The top of the list of divs would have 5px margin from the top, the bottom of the list would be 5px from the bottom, however each space inbetween the divs would be 10px (twice the spacing) and it would look wierd. With collapsed margins you can set the top and bottom margin equal to 5px, and all the space before, after, AND BETWEEN the divs would all be 5px.

Its stupid.

Solution: try to use padding AS MUCH AS POSSIBLE.

Bob Fincheimer
It's not stupid. You just have to remember that the margin isn't the same as the padding.
JAB
+14  A: 

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 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."

VoteyDisciple
I never knew this, but I'm glad I do now! Very interesting.
Jack Roscoe
+1. The same logic applies outside CSS. For example in Microsoft Word, if there is a margin of 12px after a title and of 6px before the paragraph, if the paragraph follows the title, there will be 12px space, not 18px.
MainMa