[面试官]聊一聊BFC

171 阅读2分钟

BFC

全称:块级格式化上下文(block formating context,BFC)
BFC是网页的一块区域,元素基于这块区域布局,将内部的内容与外部的上下文隔离开(内容指子元素)

如何创建一个BFC?


html(html本身就是一个BFC)
float:left,right
overflow:hidden,auto,scroll
display:inline-block,table-cell,table-caption,flex,inline-flex,grid,inline-grid, position:absolute,fixed

用来做什么?

防止外边距折叠

外边距折叠:举个栗子,食堂打饭排队,因为疫情要求每个人要离对方一米,我离你一米,你离我一米,我们的距离还是一米。

同级外边距折叠

//上下外边距发生了重叠
<style>
    .box1{
        width: 50px;
        height: 50px;
        background-color: rgb(147, 147, 228);
        margin: 50px;
    }
</style>
<body>
    <div class="box1"></div>
    <div class="box1"></div>
</body>

image.png
我第一反应是给box1加上overflow:auto让其创建一个BFC,我们来试一试。

    .box1{
        overflow: auto;
        width: 50px;
        height: 50px;
        background-color: rgb(147, 147, 228);
        margin: 50px;
    }

image.png
发现并没有消除折叠效果,给我整不会了?直到又仔细的看了一遍MDN,推测出定义中的内部内容指的是区域内的子元素,

<style>
...
   .wrapper{
         overflow: auto;
         }
</style>
<body>
      <div class="box1"></div>
      <div class="wrapper">
           <div class="box1"></div>
      </div>
</body>


我尝试给其中一个元素外套一个类名为wrapper的元素,并使其创造BFC,box1就属于wrapper内部的元素,我们来试一试。

image.png 折叠效果消除了!

嵌套外边距折叠

  <style>
        .box1 {
            width: 100px;
            height: 100px;
            background-color: rgb(147, 147, 228);
            margin: 100px;
        }
        .box2{
            width: 50px;
            height: 50px;
            background-color: black;
            margin: 25px;
        }
    </style>

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

image.png
box1和box2的外边距发生了折叠,我们为box1创建BFC试一试.

    .box1 {
            width: 100px;
            height: 100px;
            background-color: rgb(147, 147, 228);
            margin: 100px;
            overflow: auto;
        }

image.png消除了折叠。

消除浮动带来的影响

float:浮动,这个属性最早设计是为了让文档围绕设置了float的元素排列,举个栗子。

    <style>
        img {
            float: left;
            width: 300px;
        }
        .describe{
            width: 350px;
        }
    </style>
    <body>
        <div class="wrapper">
            <img src="https://img.hbs520.xyz/cat/cat.webp">
            <div class="describe">猫猫没有坏心眼,猫猫没有坏心眼,猫猫没有坏心眼,猫猫没有坏心眼,</div>
        </div>
    </body>

image.png

消除外部浮动的影响

那我又要它向左浮动,又不要它文字围绕的效果,怎么办?那就让文字消除外部浮动的影响!

   .describe{
            width: 350px;
            overflow: auto;//让该容器创建BFC
        }

image.png

消除内部浮动的影响

当我们尝试给wrapper加上背景色。

      .wrapper{
            background-color:rgb(167, 167, 218);
        }

image.png
发现了有问题!猫猫没有把wrapper的高度撑起来!如果不浮动,猫猫应该勇敢的撑起wrapper的高度!
既然猫猫不作为,那我们就来作为!

        //使wrapper创建BFC,BFC会消除内部浮动带来的影响。
        .wrapper{
            background-color:rgb(167, 167, 218);
            overflow: auto;
        }

image.png
如有错误,欢迎指正,您的指正是我进步的动力,如有帮助到您,何其荣幸。