块级格式上下文(BFC)

128 阅读1分钟

「这是我参与2022首次更文挑战的第8天,活动详情查看:2022首次更文挑战」。

哈喽,我是刘十一,今天我们一起看看BFC。

BFC的理解

块级格式上下文(Block-level Format Context)。 指一个独立的块级渲染区域,只有Block-level Box参与,该区域用一套渲染规则来约束块级盒子的布局,且与区域外无关。

现象

  • 一个盒子不设置height,当内容子元素都浮动时,无法撑起

  • 这个盒子没有形成BFC

如何创建BFC

  • 方法一:float的值不是none (eg:left、right、both)
  • 方法二:position的值不是static或者relative(eg:absolute、fiexd)
  • 方法三:display的值为table-cell, table-caption, inline-block、flex、grid中的任何一个
  • 方法四:overflow:hidden;(推荐) (eg:auto、scroll)

练一练

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>bfc</title>
    <style>
      .father {
        /* float: left; */
        /* position: relative; */
        /* display: inline-block; */
        overflow: hidden;
      }
      .son {
        width: 300px;
        height: 300px;
        background-color: blue;
        border: 1px solid #2f2f2f;
        float: left;
      }
    </style>
  </head>
  <body>
    <div class="father">
      <div class="son"></div>
      <div class="son"></div>
      <div class="son"></div>
      <a href="http://www.baidu.com">baidu</a>
    </div>
  </body>
</html>

BFC其他作用

  • BFC可以取消盒子margin塌陷
  • BFC可以阻止元素被浮动元素覆盖
<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>margin塌陷</title>
    <style>
      .father {
        width: 200px;
        height: 300px;
        background-color: hotpink;
        /* overflow: hidden; */
        /*不形成bfc  margin将塌陷连带这父盒子也会一起距离top 20px*/
      }
      .son {
        width: 100px;
        height: 100px;
        background-color: blue;
        margin-top: 20px;
      }
    </style>
  </head>
  <body>
    <div class="father">
      <div class="son"></div>
    </div>
  </body>
</html>
<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>阻止浮动元素覆盖</title>
    <style>
      .son {
        width: 200px;
        height: 200px;
        background-color: hotpink;
        float: left;
      }
      .last-son {
        width: 200px;
        height: 300px;
        background-color: blue;
        margin-top: 20px;
        /* overflow: hidden; */
        /*阻止浮动元素覆盖*/
      }
    </style>
  </head>
  <body>
    <div>
      <div class="son"></div>
      <div class="son"></div>
      <div class="last-son"></div>
    </div>
  </body>
</html>