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

HTML

Matthew Francis
Matthew Francis
6,967 Points

Margin collapse

Say I have a parent <div> with no margin and padding. Then I have a child <p> inside the <div> with a margin of 100px. The 100px will break out of the parent. Is the only solution/best practice is to add margin:1px; to <div>? or is it not recommended since you're adding 1px and that's not exactly what you want.

1 Answer

Austin Whipple
Austin Whipple
29,725 Points

Hi Matthew,

That can be pretty annoying when it's not what you're looking to achieve. First, here's some more information on margin collapse from MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing

Second, in cases where I want to specifically control that sort of situation, I usually target that p and remove the padding. You can do this in a number of ways, using a whole bunch of different combinator options, but I tend to use :last-child most as I find it a good mix of flexible, yet specific.

Matthew Francis
Matthew Francis
6,967 Points

Ahh so by removing the padding of <p> but keeping the margin. The margin won't break out of the parent? Also, what if I do want padding and margin for<p>?

Austin Whipple
Austin Whipple
29,725 Points

As far as I'm aware, padding should not impact margin collapse at all. It's simply added whitespace inside an element rather than outside an element.

If you want margin for the p element, you'll have to adjust according to the rules of vertical margin collapsing, knowing that the larger or the two adjacent margins will absorb the other. This is where using an appropriate selector comes in because you'll have to build a special case for that paragraph to either overcome the margin collapse problem or adjust and add the margin elsewhere (like the parent element instead).