search

Home  >  Q&A  >  body text

Why doesn't this CSS margin-top style work?

<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粉512729862P粉512729862504 days ago476

reply all(2)I'll reply

  • P粉141035089

    P粉1410350892023-08-24 21:55:31

    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;
    }
    

    reply
    0
  • P粉170438285

    P粉1704382852023-08-24 21:55:02

    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:

    reply
    0
  • Cancelreply