I tried to add margin
values on a div
inside another div
. All works fine except the top value, it seems to be ignored. But why?
Code:
#outer {
width: 500px;
height: 200px;
background: #FFCCCC;
margin: 50px auto 0 auto;
display: block;
}
#inner {
background: #FFCC33;
margin: 50px 50px 50px 50px;
padding: 10px;
display: block;
}
<div id="outer">
<div id="inner">
Hello world!
</div>
</div>
W3Schools has no explanation to why margin
behaves this way.
You're actually seeing the top margin of the
#inner
element collapse into the top edge of the#outer
element, leaving only the#outer
margin intact (albeit not shown in your images). The top edges of both boxes are flush against each other because their margins are equal.Here are the relevant points from the W3C spec:
You can do any of the following to prevent the margin from collapsing:
The reason the above options prevent the margin from collapsing is because:
The left and right margins behave as you expect because: