Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of CSS collapsing margins?

Tags:

css

w3c

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?

like image 570
Tom Avatar asked Jun 18 '10 13:06

Tom


People also ask

What is collapsing in CSS?

Collapsing margins happen when two vertical margins come in contact with one another. If one margin is greater than the other, then that margin overrides the other, leaving one margin.

Is CSS margin collapsing only happens with?

Margin collapsing only happens in the block-direction. This is true even if you change the writing-mode or use logical properties. The largest margin “wins”

How do I collapse a margin in CSS?

In the example above, the <h1> element has a bottom margin of 50px and the <h2> element has a top margin set to 20px. Common sense would seem to suggest that the vertical margin between the <h1> and the <h2> would be a total of 70px (50px + 20px). But due to margin collapse, the actual margin ends up being 50px.

What is box sizing and margin collapse CSS?

The top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the individual margins (or just one of them, if they are equal), a behavior known as margin collapsing. Note that the margins of floating and absolutely positioned elements never collapse.


1 Answers

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

like image 146
VoteyDisciple Avatar answered Sep 20 '22 17:09

VoteyDisciple