CSS CSS Layout Basics Getting Started with CSS Layout Why Vertical Margins Collapse

What is the purpose of collapsing vertical margins?

Why do browsers collapse vertical margins? I can't think of why this would be a desired behavior.

2 Answers

The function a margin serves is to ensure that an element should have X pixels of space on the top/bottom of it. If you had two paragraphs stacked in a div, each with margin:10px 0; without collapsing you would have 20 pixels between them. It makes sense when you think of it in the context of "I want paragraphs to always have 10px of space above and below them".

Here's an excellent post on the topic: http://complexspiral.com/publications/uncollapsing-margins/

Thanks for the response and the resource, guess I'll just have to remember to do box-sizing and add a little padding to avoid surprises.

Million Asseghegn
Million Asseghegn
3,845 Points

when there is no border padding that protects it