CSS-外边距折叠

82 阅读1分钟

理解

区块的上下外边距有时会合并(折叠)为单个边距,其大小为两个边距中的最大值(或如果它们相等,则仅为其中一个),这种行为称为外边距折叠

产生外边距折叠的情况

  1. 相邻兄弟元素
  2. 父元素没有与子元素分隔

    父元素没有设定 border、padding、行内元素、也没有创建BFC、高度、最小高度等

  3. 空的区块

相邻兄弟元素

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .box {
      width: 100px;
      height: 100px;
    }
    .box1 {
      background-color: green;
      margin-bottom: 10px;
    }
    .box2 {
      background-color: red;
      margin-top: 10px;
    }

    /* 创建BFC,可以解决该问题 */
    .container-bfc {
      display: flow-root;
    }
  </style>
</head>
<body>
  <!-- 两个兄弟元素的margin-bottom和margin-top,会合并 -->
  <p>合并</p>
  <div class="box box1"></div>
  <div class="box box2"></div>
  
  <p>解决margin合并</p>
  <div class="box box1"></div>
  <div class="container-bfc">
    <div class="box box2"></div>
  </div>

</body>
</html>

image.png

父元素与子元素margin重叠

  • 父元素不是BFC
  • 父元素没有 padding、border 属性
  • 父元素与第一个子元素直接没有行内元素进行分隔
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .container {
      width: 200px;
      height: 200px;
      background-color: red;
      margin-top: 10px;
    }
    .box {
      width: 100px;
      height: 100px;
      background-color: green;
      margin-top: 10px;
    }


    .container-bfc {
      /* 创建BFC,可以解决该问题 */
      overflow: hidden;

      /* 或者给父元素设置 border、padding 等 */
      /* border-top: 1px solid #000 */
      /* padding-top: 10px; */
    }

  </style>
</head>
<body>
  <body>
    <p>合并</p>
    <div class="container">
      <div class="box"></div>
    </div>

    <p>解决合并</p>
    <div class="container container-bfc">
      <!-- 若有行内元素,则不会margin重叠 -->
      <!-- <span>行内元素</span> -->
      <div class="box"></div>
    </div>
  </body>

</body>
</html>

image.png

空元素

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .container {
      width: 200px;
      height: 200px;
      background-color: red;
    }
    .box {
      background-color: green;
      margin: 50px;
    }

    /* 创建BFC,可以解决该问题 */
    .container-bfc {
      overflow: hidden;
    }

  </style>
</head>
<body>
  <body>
    <p>合并</p>
    <div class="container">
      <div class="box"></div>
    </div>

    <p>解决合并</p>
    <div class="container container-bfc">
      <div class="box"></div>
    </div>
  </body>

</body>
</html>

image.png