I try to add margin values on a div inside another div. All works fine except the top value, it seems to be ignored. But why?
What I expected:
What I get:
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 have no explanation to why margin behave 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:
The reason why doing any of the following prevents the margin from collapsing:
div
elementsdiv
elements inline blocksoverflow
of#outer
toauto
(or any value other thanvisible
)Is because:
The left and right margins behave as you expect because:
Use
padding-top:50px
for outer div. Something like this:Note: padding will increase the size of your div. In this case if the size of your div is important, I mean if it must have a specific height. decrease the height by 50px.:
try this:
http://jsfiddle.net/7AXTf/
Good luck
I guess setting the position property of the #inner div to relative may also help achieve the effect. But anyways I tried the original code pasted in the Question on IE9 and latest Google Chrome and they already give the desirable effect without any modifications.
Not sure why what you have doesn't work, but you can add
overflow: auto;
to the outer div.
Try using
display: inline-block;
on the inner div.