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!

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


Why does my margin betwen two elements take the value of the biggest margin?

<head> <style> h1 { margin: 0 0 30px 0; border: 2px solid red; }

h2 { margin: 20px 0 0 0; border: 2px solid red; } </style> </head> <body>

<p>The margin I end up with is 30px, the 20px top margin of the h2 element is completely ignored</p>

<h1>Heading 1</h1> <h2>Heading 2</h2>

</body> </html>

Is this a glitch in CSS or this is some feature that it has?

1 Answer

Dane Parchment
Dane Parchment
Treehouse Moderator 11,073 Points

This is a behavior from CSS known as Margin Collapsing.

I recommend reading that article to find out why it occurs, then this about what you need to know about it, and finally this answer on stack overflow will give you an idea of what to do to solve the behavior.

In your case margin collapse is happening via adjacent elements so to solve it you can set any one of your elements (or both) to have a display: inline-block; that should solve your issue

Thank you, that helped a lot.