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

Why applying margin-top and bottom with display block does not work on child div, but on the parent, it works.

<!DOCTYPE html>
<html>
<head>
<style>
 html,body{
 height:100vh;
 width:100vw;
 }
 *{margin:0;
 padding:0;
 box-sizing:border-box;
 }
</style>
</head>
<body>
 <div class="parent" style="height:50%;width:100px;display:block;margin:22px auto;background:red;">

 <div class="child" style="margin:23px;display:block;height:20px;background:blue;width:20px;"></div>

  <!---
When I use display inline-block, it solves my issues, but I want to know why
 because block and inline-block respect margin-top and bottom, but
 margin-top and bottom are not working when I set the display to block on the child
-->
</div>
</body>
</html>

1 Answer

Cameron Childres
Cameron Childres
11,820 Points

Your margins are collapsing on each other, making the greater of the two apply to the parent. If you add a border or padding to the parent div you'll see your margin applied.

Margin collapse happens to block-level elements and doesn't apply to inline-block, which is why you see both margins when you change the child to "display: inline-block".

From a helpful MDN guide:

If there is no border, padding, inline part, block formatting context created, or clearance to separate the margin-top of a block from the margin-top of one or more of its descendant blocks ... then those margins collapse. The collapsed margin ends up outside the parent.

You might also want to check out this treehouse video on vertical margin collapse. I recommend going through the entirety of the CSS Layout Basics Course as it provides a solid foundation for learning how to position content on a page.

Side note: I'm no expert so take this with a grain of salt, but I believe "display:block;" is redundant on the <div> elements -- they are already block level by default. If you remove this property you shouldn't see any change.