YBFACC / blog

仅记录个人学习使用
3 stars 0 forks source link

BFC #16

Open YBFACC opened 4 years ago

YBFACC commented 4 years ago

BFC

介绍

块格式化上下文(Block Formatting Context,BFC) 是Web页面的可视CSS渲染的一部分,是块盒子的布局过程发生的区域,也是浮动元素与其他元素交互的区域。

以下设置会产生BFC

以上引用来自MDN

我的理解

我们可以知道根元素<html>就是一个 BFC。当我们在页面中开启新的BFC,这就像在在旧 Html 中,开启了一个新的 Html 。这两个 Html 不能相互影响。

BFC的范围

  <div id="div_1" class="BFC">
    <div id="div_2">
      <div id="div_3"></div>
    </div>

    <div id="div_4">
      <div id="div_5"></div>
    </div>

    <div id="div_6" class="BFC">
      <div id="div_7"></div>
      <div id="div_8"></div>
    </div>
  </div>

使用

  1. 浮动定位和清除浮动时只会应用于同一个BFC内的元素。
  2. 浮动不会影响其它BFC中元素的布局,而清除浮动只能清除同一BFC中在它前面的元素的浮动。(不会重叠浮动元素)
  3. 外边距折叠也只会发生在属于同一BFC的块级元素之间。

测试

高度塌陷

  <style>
    .box {
      border: 10px solid red;
    }
    .left {
      width: 50px;
      height: 50px;
      background-color: aqua;
      float: left;
    }
  </style>
<body>
  <div class="box">
    <div class="left"></div>
  </div>
</body>

1_change

经典的高度塌陷。想解决它,利用上面的属性1。我们给 .box 添加上 overflow: hidden; 来开启BFC

2_change

清除前一个浮动的影响

  <style>
    .box1 {
      height: 100px;
      width: 100px;
      float: left;
      background: lightblue;
    }

    .box2 {
      width: 200px;
      height: 200px;
      background: #eee;
    }
  </style>

<body>
  <div class="box1">左浮动</div>
  <div class="box2">awecscrsc
    dadaedaed
    adaedaedadaedewdrgvr
    vcercrcwcnciwenciwen
    wcwinciweicmweomcowe
  </div>
</body>

5_change

可以看到这里的 box1 出现了环绕的效果。这里清除前一个浮动的影响,可以使 box2 开启 BFC。

6_change

外边距折叠

  <style>
    .box1 {
      height: 100px;
      width: 100px;
      background: lightblue;
      margin: 50px;
    }

    .box2 {
      width: 100px;
      height: 100px;
      background: #eee;
      margin: 50px;
    }
  </style>

<body>
  <div class="box1"></div>
  <div class="box2"></div>
</body>

10_change

可以看到这里上下边距出现了重叠。解决此方法可以给 box2 套一层 wrap。

  <style>
    .box1 {
      height: 100px;
      width: 100px;
      background: lightblue;
      margin: 50px;
    }

    .box2 {
      width: 100px;
      height: 100px;
      background: #eee;
      margin: 50px;
    }

    .wrap {
      overflow: hidden;
    }
  </style>

<body>
  <div class="box1"></div>
  <div class="wrap">
    <div class="box2"></div>
  </div>
</body>

11_change

参考

块格式化上下文

深入理解BFC

学习 BFC (Block Formatting Context)