Why does this CSS margin-top style not work?

前端 未结 12 1947
醉梦人生
醉梦人生 2020-11-21 04:54

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:
<

相关标签:
12条回答
  • 2020-11-21 05:22

    try this:

    #outer {
        width:500px; 
        height:200px; 
        background:#FFCCCC;
        margin:50px auto 0 auto;
        display:table;
    }
    #inner {
        background:#FFCC33;
        margin:50px 50px 50px 50px;
        padding:10px;
        display:block;
    }​
    

    http://jsfiddle.net/7AXTf/

    Good luck

    0 讨论(0)
  • 2020-11-21 05:23

    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.

    0 讨论(0)
  • 2020-11-21 05:26

    Just for a quick fix, try wrapping your child elements into a div element like this -

    <div id="outer">
       <div class="divadjust" style="padding-top: 1px">
          <div id="inner">
             Hello world!
          </div>
       </div>
    </div>
    

    Margin of inner div won't collapse due to the padding of 1px in-between outer and inner div. So logically you will have 1px extra space along with existing margin of inner div.

    0 讨论(0)
  • 2020-11-21 05:30

    Not exactly sure why, but changing the inner CSS to

    display:inline-block;
    

    seems to work;

    0 讨论(0)
  • 2020-11-21 05:30

    Have you tried !important before all, it will force everything:

    margin:50px 50px 50px 50px !important;
    
    0 讨论(0)
  • 2020-11-21 05:31

    Use padding-top:50pxfor outer div. Something like this:

    #outer {
        width:500px; 
        height:200px; 
        background:#FFCCCC;
        margin:50px auto 0 auto;
        display:table;}
    

    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.:

    #outer {
        width:500px; 
        height:150px; 
        background:#FFCCCC;
        margin:50px auto 0 auto;
        display:table;}
    
    0 讨论(0)
提交回复
热议问题