林秀栋的技术博客

垂直外边距合并的问题及解决方法

嵌套元素

<style>
    *{
        margin: 0;
        padding: 0;
    }
    .outer{
        height: 200px;
        width: 200px;
        margin-top: 50px;
        background: black;
    }
    .inner{
        height: 100px;
        width: 100px;
        margin-top: 100px;
        background: red;
    }
</style>

<div class="outer">
    <div class="inner"></div>
</div>

上面代码我们的本意时希望outer距离顶部50px,inner距离outer顶部100px

但实际情况是inner会贴着outer顶部,而outer会距离顶部100px(取数值大的那个)

解决

  1. 可以为父元素定义1px的上边框(border-top)或上内边距(padding-top)
  2. inner中的margin-top: 100px改为由outer中的padding-top: 100px实现
  3. 可以为父元素添加overflow: hidden
  4. 给任意一个盒子设置定位为absolute或fixed(relative无效)
  5. 设置任意一个盒子为display: inline-block

相邻元素

当上下相邻的两个块元素相遇时,如果上面的元素有下外边距margin-bottom,下面的元素有上外边距margin-top,则他们之间的垂直间距不是margin-bottom与margin-top之和,而是两者中的较大者。这种现象被称为相邻块元素垂直外边距的合并(也称外边距塌陷)。

<style>
    *{
        margin: 0;
        padding: 0;
    }
    #a{
        height: 100px;
        width: 100px;
        margin-bottom: 50px;
        background: black;
    }
    #b{
        height: 100px;
        width: 100px;
        margin-top: 100px;
        background: red;
    }
</style>

<div id="a"></div>
<div id="b"></div>

解决

  1. 给任意盒子设置display: inline-block
  2. 给第二个盒子设置定位为absolute或fixed(relative无效)
  3. 给第二个盒子设置浮动