首页 > 技术文章 > margin塌陷(collapse)

webliu 2015-08-11 15:41 原文

1.当两个对象为上下关系时,而且都具备margin属性时,上面的margin-bottom与下面的margin-top会发生塌陷

  • 当margin-bottom和margin都为正数时,结果为两者之间的最大值
     <div id="a"></div>
     <div id="b"></div>
    
    
    
    #a{
        background:red;
        width:150px;
        height:150px;
        margin-bottom:50px;
     }
     #b{
        background:green;
        width:100px;
        height:100px;
        margin-top:20px;
     }
     
    
    
     
  • 当margin-bottom和margin-top都为负时,结果为两者绝对最较大的那个值。
     <div id="a"></div>
     <div id="b"></div>
    
    
    #a{
        background:red;
        width:150px;
        height:150px;
        margin-bottom:-50px;
     }
     #b{
        background:green;
        width:100px;
        height:100px;
        margin-top:-40px;
     }
     
    
     
  • 当margin-bottom和margin-top为一正一负时,结果为两者之和。
    <div id="a"></div>
    <div id="b"></div>
    
    
    #a{
        background:red;
        width:150px;
        height:150px;
        margin-bottom:-50px;
     }
     #b{
        background:green;
        width:100px;
        height:100px;
        margin-top:20px;
     } 


2.当两个对象为上下包含关系

  • 父元素无填充内容,且没有设置border时,子元素的margin-top不会起作用
     <div id="a">
        <div id="b"></div>
     </div>
    
    #a{
        background:red;
        width:150px;
        height:150px;
     }
     #b{
        background:green;
        width:100px;
        height:100px;
        margin-top:20px;
     }
  • 父元素设置border属性,子元素的margin-top起作用
    #a{
        background:red;
        width:150px;
        height:150px;
        border:1px solid #000;
     }
     #b{
        background:green;
        width:100px;
        height:100px;
        margin-top:20px;
     }
     
    
     <div id="a">
        <div id="b"></div>
     </div>

  • 父元素有填充内容,子元素的margin-top会起作用,当margin-top小于填充内容时,距离为填充内容的高度
    #a{
        background:red;
        width:150px;
        height:150px;    
     }
     #b{
        background:green;
        width:100px;
        height:100px;
        margin-top:20px;
     }
     
     <div id="a">liuliu
        <div id="b"></div>
     </div>

  • 解决父元素塌陷的方法还有,为父元素添加overflow:hidden;,或float非none属性,也可为子元素添加float非none属性

如果有新发现将继续补充。

 

推荐阅读