Why doesn't this CSS margin-top style work?
P粉512729862
2023-08-23 23:07:58
<p>I tried adding a <code>margin</code> value on a <code>div</code> inside another <code>div</code>. Everything works fine except the highest value, which seems to be ignored. But why? </p>
<p><strong>My expectations:</strong></p><p><br /></p>
<p><strong>What I got:</strong></p><p><br /></p>
<p><strong>Code: </strong></p>
<p><br /></p>
<pre class="brush:css;toolbar:false;">#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;
}</pre>
<pre class="brush:html;toolbar:false;"><div id="outer">
<div id="inner">
Hello world!
</div>
</div></pre>
<p><br /></p>
<p>W3Schools does not explain why this happens with <code>margin</code>. </p>
Try using
display: inline-block;
on the innerdiv
. like this:What you actually see is the top margin of the
#inner
element collapses to the top edge of the#outer
element, leaving only the#outer
Margins are intact (although not shown in the image). The top edges of the two boxes are flush with each other because their margins are equal.The following are relevant points from the W3C specification:
You can do any of the following to prevent margins from collapsing:
The above options prevent margin collapse for the following reasons:
The left and right margins behave as you expect because: