BFC margin塌陷与合并

BFC

BFC是一个独立的布局环境,其中的元素布局是不受外界的影响,并且在一个BFC中,都会垂直的沿着其父元素的边框排列。

BFC的布局规则

  • 内部的Box会在垂直方向,一个接一个地放置。

  • Box垂直方向的距离由margin决定。属于同一个BFC的两个相邻Box的margin会发生重叠。

  • BFC的区域不会与float box重叠。

  • BFC就是页面上的一个隔离的独立容器,容器里面的子元素不会影响到外面的元素。反之也如此。

  • 计算BFC的高度时,浮动元素也参与计算。

创建BFC

  • 1、float的值不是none。
  • 2、position的值不是static或者relative。
  • 3、display的值是inline-block、table-cell、flex、table-caption或者inline-flex
  • 4、overflow的值不是visible

margin塌陷

<style>
        body{
            background-color:#000;
        }
     .wrapper{
         width:200px;
         height:200px;
         background-color:red;
         margin-top:100px;
     }
     .box{
        width:50px;
         height:50px;
         background-color:#eee;
         opacity:0.8;
     }
    </style>
</head>
<body >
        <div class="wrapper">
            <div class="box"></div>
        </div>
</body>

现在给里面的小方块设置margin-top:100px;发现两个方块位置没动;

而当给里面的小方块设置margin-top:150px;小方块带着大方块往下移动了50px

<style>
    body{
        background-color:#000;
    }
 .wrapper{
     width:200px;
     height:200px;
     background-color:red;
     margin-top:100px;
 }
 .box{
    width:50px;
     height:50px;
     background-color:#eee;
     opacity:0.8;
     margin-top: 150px;
     /* margin-top: 100px; */
 }
</style>
</head>
<body >
    <div class="wrapper">
        <div class="box"></div>
    </div>
</body>

原理:父子嵌套元素在垂直方向的margin,父子元素是结合在一起的,他们两个的margi会取其中最大的值.

正常情况下,父级元素应该相对浏览器进行定位,子级相对父级定位.

但由于margin的塌陷,父级相对浏览器定位.而子级没有相对父级定位,子级相对父级,就像坍塌了一样.

margin塌陷解决方法

  • 1.给父级设置边框或内边距
  • 触发bfc(块级格式上下文),改变父级的渲染规则

margin合并

两个兄弟结构的元素在垂直方向上的margin是合并的

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
                  margin: 0;
                  padding: 0;
              }
              body {
                  background-color: #000;
              }
              .box1 {
                  height: 30px;
                  margin-bottom: 100px;
                  background-color: red;
              }
              .box2 {
                  height: 30px;
                  margin-top: 100px;
                  background-color: aqua;
              }
      </style>
</head>
   
      <body >
          <div class="box1"></div>
          <div class="box2"></div>
      </body>
</html>

margin合并解决方法

使用bfc来解决根据需求选不同的方案

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。