面试复盘之一/BFC

781 阅读1分钟

定义

(block formatting context)块级格式化上下文。

特点:

1,同一个bfc的两元素margin重叠,如果用div包裹p,则两个p属于不同bfc,不会重叠

<!DOCTYPE html>
<head>
  <style>
    p{
      margin: 30px;
      background-color: yellow;
    }
  </style>
</head>
<body>

  <p>margin1</p>
  <p>margin2</p>
</body>

2,BFC区域不会与float重叠,可以实现自适应两栏布局
触发bfc前:

<!DOCTYPE html>
<head>
  <style>
    .class1{
      float: left;
      width: 100px;
      height: 100px;
      background-color: yellow;
    }
    .class2{
      height: 300px;
      background-color: blue;
    }
  </style>
</head>
<body>
  <div class="class1">

  </div>
  <div class="class2">

  </div>
</body>

触发bfc后: 3,浮动元素也参与高度计算,可以用来清除浮动
触发bfc前:

<!DOCTYPE html>
<head>
  <style>
    .class1{
      float: left;
      width: 400px;
      height: 200px;
      background-color: yellow;
    }
    .class2{
      height: 100px;
      background-color: blue;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="class1">

    </div>
    <div class="class2">
  
    </div>
  </div>
</body>

触发bfc后: 4,内部盒子会在竖直方向上一个个放置。
5,BFC是一个隔离的独立容器,容器里的子元素不会影响到外部元素,外部元素也不会影响到里面元素。
6,元素的margin-left与其包含块的border-left相接触。

触发BFC的方式:

1,根元素
2,float的值非none
3,position值非static或relative
4,overflow非visible
5,display为inline-block、table-cell、flex、table-caption或者inline-flex