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

Fix for margin collapse between two adjacent siblings

I am working on understanding margin collapse. I have been toying around with it in codepen to try to get a better understanding of when it happens and why and how to fix it. I feel I have a decent understanding of it now, however one thing is really bugging me. I have been researching how to fix these margin collapses and have been having issues with adjacent siblings. I've found an explanation of margin collapses at https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing but for the first example of "Adjacent Siblings" it does not give a fix.

Is there no fix for margin collapse between two adjacent siblings? Below is a link to a codepen I drew up for an example.

http://codepen.io/MrAdam/pen/EyKPGY

1 Answer

Steven Parker
Steven Parker
243,656 Points

If you don't mind the extra pixel, you can put an empty element between the siblings that has an explicit 1px height.

Otherwise, you might want to re-think the use of margin and consider using padding instead. Apply a wrapper element to each sibling, and set the padding of the wrapper as you would have set the margin of the sibling.