likes
comments
collection
share

面试官:说说你理解的「BFC」

作者站长头像
站长
· 阅读数 44

什么是 BFC

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

简单来说就是设置了BFC的元素就形成独立的区域,BFC的中内部元素的渲染不会影响到外部元素,一个元素只能存在于一个BFC空间

形成BFC的条件(常见)

  1. 浮动元素flort 不为 none
  2. 绝对定位元素 position 为 absolute 或者 fixed
  3. 块级元素 overflow 不是 visible 或者 clip
  4. 行内块元素 display 为 inline-block

📦场景一:避免两个相邻的元素外边距重叠

当创建两个div,其中一个外边距设置成10px,另一个外边距设置成20px,此时两个div的外边距会发生重叠,这是一种规范,块的上外边距margin-top和下外边距margin-bottom会发生重叠,合并成单个边距,并取最大的边距值。

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

<style>
  .box1 {
    width: 100px;
    height: 100px;
    border: 1px solid red;
    margin-bottom: 10px;
  }

  .box2 {
    width: 100px;
    height: 100px;
    border: 1px solid rgb(82, 77, 77);
    margin-top: 20px;
  }
</style>
如下图所示:

面试官:说说你理解的「BFC」

🤔解决办法:将其中一个盒子外面添加一个BFC容器。
body>
  <div class="bfc">
    <div class="box1"></div>
  </div>
  <div class="box2"></div>
</body>

<style>
  /* 案例一 */
  .box1 {
    width: 100px;
    height: 100px;
    border: 1px solid red;
    margin-bottom: 10px;
  }

  .box2 {
    width: 100px;
    height: 100px;
    border: 1px solid rgb(82, 77, 77);
    margin-top: 20px;
  }

  .bfc {
    overflow: hidden;
  }
</style>
如下图所示:两个盒子的外边距不会发生重叠

面试官:说说你理解的「BFC」

📦场景二:避免父元素高度塌陷

当子元素设置了高度并设置了浮动,父元素没有设置高度,此时父元素就会出现高度塌陷。

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

<style>
  .box1 {
    width: 100px;
    height: 100px;
    border: 1px solid red;
    float: left;
  }
</style>
如下图所示:container的高度是0

面试官:说说你理解的「BFC」

解释:父元素的高度是子元素撑开的,当子元素设置浮动的时候,子元素形成了一个BFC元素,又由于BFC元素会形成独立的区域,此时浮动的子元素会脱离父元素的文档流。解决方案有很多种,其中一种就是可以将父元素设置成BFC容器,给父元素设置overflow:hidden。

<body>
  <div class="container bfc">
    <div class="box1"></div>
  </div>
</body>

<style>
  .box1 {
    width: 100px;
    height: 100px;
    border: 1px solid red;
    float: left;
  }

  .bfc {
    overflow: hidden;
  }
</style>
如下图所示:container的高度是102px

面试官:说说你理解的「BFC」

📦场景三:阻止元素被浮动元素覆盖

两个同级元素,其中一个元素设置了浮动,另外一个没有设置浮动,这个时候浮动的元素就会覆盖没有浮动的元素。

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

<style>
  .box1 {
    width: 100px;
    height: 100px;
    background-color: rgb(80, 79, 77);
    float: left;
  }

  .box2 {
    width: 200px;
    height: 200px;
    background-color: bisque;
  }
</style>
如下图所示:

面试官:说说你理解的「BFC」

这个场景和上面的类似,都是浮动引起的,解决办法有很多,其中最简单的就是将另一个盒子也设置浮动,让两个盒子都处于BFC中。

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

<style>
  .box1 {
    width: 100px;
    height: 100px;
    background-color: rgb(80, 79, 77);
    float: left;
  }

  .box2 {
    width: 200px;
    height: 200px;
    background-color: bisque;
    float: left;
  }
</style>
如下图所示:

面试官:说说你理解的「BFC」

转载自:https://juejin.cn/post/7242249906257625145
评论
请登录