Skip to content

五、BFC 规范 和 浏览器差异

**TIP

BFC (Box Formatting Context ,块级格式上下文)是页面上的一个隔离的独立容器 容器里的子元素不会影响到外面的元素,反之亦然 如:一个盒子不设置 height,当内容子元素都浮动时,无法撑起自身

原因是:这个盒子没有形成 BFC ![[Pasted image 20260228115106.png]]

1、创建 BFC

**TIP

方法 1:float 的值不是 none 方法 2:position 的值不是 static 或者 relative 方法 3:display 的值是 inline-block、flex 或 inline-flex 方法 4:overflow:hidden;

<!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>创建BFC - arry老师</title>
    <style>
      .box {
        width: 500px;
        border: 5px solid red;
        /* 
            方法1:float的值不是none 
            该方法可以实现效果,但没有意义,不可能随意给盒子设置浮动
        */
        /* float: left; */

        /* 
            方法2:position的值不是static或者relative 
            该方法可以实现效果,但不靠谱
        */
        /* position: absolute; */

        /* 
            方法3:display的值是 inline-block、flex 或 inline-flex 
            该方法可以实现效果,但,没有意义,可能随便改变盒子的为行内块,获取其他的
        */
        /* display: inline-block; */
        /* display: flex; */
        /* display: inline-flex; */

        /* 
            方法4:overflow:hidden;
            该方法可以实现效果,但是,不能满足所有的场景
        */
        /* overflow: hidden; */
      }
      .box .c1 {
        width: 200px;
        height: 200px;
        background-color: orange;
        float: left;
      }
      .box .c2 {
        width: 200px;
        height: 200px;
        background-color: skyblue;
        float: left;
      }
    </style>
  </head>
  <body>
    <h1>创建BFC</h1>
    <p>
      BFC (Box Formatting Context
      ,块级格式上下文)是页面上的一个隔离的独立容器
    </p>

    <div class="box">
      <div class="c1"></div>
      <div class="c2"></div>
    </div>
  </body>
</html>

溢出隐藏:overflow:hidden;

溢出盒子边框的内容将会被隐藏 overflow:hidden;是非常好用的让盒子形成 BFC 的方法

2、BFC 的其他作用

**TIP

BFC 可以取消盒子 margin 塌陷 BFC 可以阻止元素被浮动元素覆盖

<style>
  p {
    width: 200px;
    height: 200px;
    background-color: orange;
    /* 垂直方向上下margin会重合 距离依然是:50 */
    margin: 50px;
  }

  /* 
    BFC作用一:可以取消盒子margin塌陷
    添加overflow:hidden; 创建BFC
  */
  div {
    overflow: hidden;
  }

  /* 
    BFC作用二:可以阻止元素被浮动元素覆盖
    没有实际意义,实际开发不会这么用,只具有理论意义,要明白
    需要并排显示的盒子,要么都浮动,要么都不写,以下的写法是不合法规范的
  */
  .box1 {
    width: 300px;
    height: 300px;
    background-color: skyblue;
    float: left;
  }

  .box2 {
    width: 200px;
    height: 200px;
    background-color: tomato;
    /* float: left; */
    overflow: hidden;
  }
</style>

<body>
  <div>
    <p></p>
  </div>

  <div>
    <p></p>
  </div>

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

3、浏览器差异

**TIP

IE6、7 浏览器使用 haslayout 机制 和 BFC 规范略有差异 比如:IE 浏览器可以使用 zoom:1 属性,让盒子拥有 layout 如果要制作兼容到 IE6、7 的网页时,尽量让网页布局变得简单,内部有浮动的盒子要设置 height 属性,规范编程,就没有问题