Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

J Tan
J Tan
11,847 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,762 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,847 Points

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

1 Answer

Steven Parker
Steven Parker
229,061 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,847 Points

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