BFC

247 阅读1分钟

1、含义

BFC(block formatting context)块级格式化上下文,它是页面中的一块渲染区域,有一套自己的渲染规则,决定元素如何对齐,内容如何进行布局,以及和其他元素的关系和相互作用。

2、布局规则

(1)内部的盒子会在垂直方向上一个个的放置。

(2)属于同一个bfc的相邻的两个box上下margin会发生重叠。

(3)bfc的区域不会与浮动的元素重叠。

(4)计算bfc元素的高度时,浮动的元素也参与计算,或者说可以解决浮动元素高度塌陷的问题。

3、触发条件 4、应用

5、案例解析

(1)外边距折叠

  • 原代码:

    <!DOCTYPE html>
     <html lang="en">
     <head>
         <meta charset="UTF-8">
         <meta name="viewport" content="width=device-width, initial-scale=1.0">
         <title>Document</title>
     </head>
     <body>
         <div class="box1"></div>
         <div class="box2"></div>
     </body>
     </html>
     <style>
         .box1 {
             width: 100px;
             height: 100px;
             background: red;
             margin-bottom: 10px;
         }
         .box2 {
             margin-top: 20px;
             width: 100px;
             height: 100px;
             background: blue;
         }
     </style>
    
  • 改后:

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

    .box {
        overflow: hidden;
    }

    .box2 {
        margin-top: 20px;
        width: 100px;
        height: 100px;
        background: blue;
    }
</style>

解析:同一个BFC下的margin会出现重叠,我们就让他们不处于一个BFC下即可

(2)解决浮动元素高度塌陷问题

   <!DOCTYPE html>
  <html lang="en">
  <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
  </head>
  <body>
      <div class="box">
          <div class="box1"></div>
          <div class="box2">fsadkfhkdshksda</div>
      </div>
  </body>
  </html>
  <style>
      .box {
          /*设置了overflow:hidden之后会让box变为BFC,它能够计算浮动的元素的高度 */
          /* overflow: hidden; */
          border: 1px solid red;
      }

      .box1 {
          float: left;
          width: 100px;
          height: 100px;
          background: red;
      }

      .box2 {
          background: blue;
      }
  </style>