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

J Tan
J Tan
11,845 Points

Why adding padding to only .main-header fixes collapse?

I tried adding padding: 1em 0; to .wrapper which contains .main-header, but it doesn't fix the collapse. I also tried adding the same padding statement to h1 tag but it doesn't fix it either.

Why does padding fix only works with .main-header class?

ywang04
ywang04
6,748 Points

As you said, .wrapper is the parent of .main-header. But the collapse doesn't occur between .wrapper and .main-header. You can set a border property to both of them to make sure there is no collapse between them. The collapse actually happens between h1 and .main-header while .main-header is the parent of h1.

J Tan
J Tan
11,845 Points

@ywang04 thanks for reminding me to turn on borders to see where the collapse is happening.

1 Answer

Steven Parker
Steven Parker
204,000 Points

There's 3 types of margin collapse: sibling, parent-child, and empty element. Padding only stops the collapse if applied to the parent in parent-child collapse, or to an empty element. It no effect on sibling collapse or when applied to the child in a parent-child collapse. For more info see Mastering margin collapsing.

One other remedy I've always found odd is setting the overflow property on one of the elements in the collapse.

J Tan
J Tan
11,845 Points

For some reason I thought since .wrapper is the parent of .main-header, it would also fix the collapse. Thanks.