Why doesn't this CSS margin-top style work?
P粉512729862
P粉512729862 2023-08-23 23:07:58
0
2
463
<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>
P粉512729862
P粉512729862

reply all(2)
P粉141035089

Try using display: inline-block; on the inner div. like this:

#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:inline-block;
}
P粉170438285

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:

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template