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

long story short- Please correct me if im wrong !

is it right to say that if there is no padding between the elements, and the only thing separating them are margins, these margins will collapse to the highest value ?

IE: if there is a margin of an element A ( a div box per say) of 20 px ; and another margin of an element B of 30 px ;

the 2 above margins will collapse to form one margin of 30 px ?

i am just trying to verify what i understood from this vid, appreciate your help! thanks !

Danny Alder
Danny Alder
9,119 Points

The moral of your story is correct. The margin will always collapse to the highest margin value. Even negative margins are affected by this behaviour. A more detailed resource can be found here: https://css-tricks.com/what-you-should-know-about-collapsing-margins/.

A good habit to get into, especially when it comes to typography, is to only ever use margin-top OR margin-bottom in your css. Never both. I usually only use margin-bottom as this mimics spacing-below attributes of page layout software that I am used to using for print work. By only setting the bottom margin of type, you can be sure that your typographic rhythm on the page will almost always be consistent while avoiding collapsing margins between headers and paragraphs.

2 Answers

Steven Parker
Steven Parker
204,006 Points

You have the right basic idea, but be aware that there are different types of margin collapse: between adjacent siblings, and between parent and first or last child elements, and empty blocks. These each have slightly different rules.

For complete details, see this MDN page on Mastering Margin Collapsing.

thank u both !