外边距合并知识

一、什么是外边距合并

外边距合并是指垂直相邻的块级元素在边距相遇时会形成一个外边距,最终的外边距以两者中较大的为准。

二.外边距合并的直观例子

1.父子之间

1.1 父元素没有margin-top,子元素有margin-top,合并后父元素的margin-top为子元素设置的,子元素的margin-top失效

演示代码如下:

<div class="box1"> 
   <div class="box2"></div> 
</div> 
.box1{height:200px;width:200px;background:gray;} 
.box2{height:100px;width:100px;background:gold;margin-top:50px;} 

1.2 父子元素都设置了margin-top,子元素实际的margin-top变为0,父元素的margin-top变为30

 

<html>
<head>

<style type="text/css">
* {
  margin:0;
  padding:0;
  border:0;
}

#outer {
  width:300px;
  height:300px;
  background-color:red;
  margin-top:20px;
}

#inner {
  width:50px;
  height:50px;
  background-color:blue;
  margin-top:30px;
}

</style>
</head>

<body>

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

<p>注释:请注意,如果不设置 div 的内边距和边框,那么内部 div 的上外边距将与外部 div 的上外边距合并(叠加)。</p>
</body>
</html>

上述两种情况的过程图解如下

 1.3一个box的bottom margin(height 为auto的情况下)与最后一个子box的bottom margin发生合并,box1与boxother的间距变成了50px而不是10,同时box3设置的margin-bottom失效了

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style type="text/css">
        .box1{height:auto;width:200px;background:gray;margin-bottom: 10px;} 
        .box2{height:100px;width:100px;background:gold;margin-top:50px;} 
        .box3{height:100px;width:100px;background:yellow;margin-bottom:50px;} 
        .boxother{width: 200px;height: 200px;background: blue;}
    </style>
</head>
<body>
<div class="box1"> 
    <div class="box2">box2</div> 
    <div class="box3">box3</div> 
</div>
<div class="boxother">boxthoer</div>
</body>
</html>

2、当元素是兄弟元素时,在不设置float和position:absolute时上面的margin-bottom和下面的margin-top会自动的合并为两者中的最大值

<html>
<head>

<style type="text/css">
* {
  margin:0;
  padding:0;
  border:0;
}

#d1 {
  width:100px;
  height:100px;
  margin-bottom:20px;
  background-color:red;
}

#d2 {
  width:100px;
  height:100px;
  margin-top:10px;
  background-color:blue;
}

</style>
</head>

<body>

<div id="d1">
</div>

<div id="d2">
</div>

<p>请注意,两个 div 之间的外边距是 20px,而不是 30px(20px + 10px)。</p>
</body>
</html>

三、哪些情况会产生外边距合并

  • 这些margin都处于普通流中,并在同一个BFC(块级格式化上下文)中;
  • 这些margin在垂直方向上是毗邻的(没有border和padding)

四、如何避免外边距合并

1.父子元素之间的外边距合并(任选一种)

  • 给父元素加一个overflow:auto 

原理:生成了新的BFC

  • 给父元素加padding
  • 给父元素设置border

原理:垂直方向上不再产生毗邻

2.同级垂直相邻元素(任选一种)

  • 给第二个盒子设置浮动属性;
  • 给第二个盒子绝对定位

原理:生成了新的BFC

给任意一个盒子加display:inline-block;

原理:垂直方向上不再产生毗邻

五、BFC知识

点击查看

原文地址:https://www.cnblogs.com/94pm/p/8492834.html