(自用面试题)BFC是什么?

150 阅读1分钟

谈到BFC,我们首先要知道什么是BFC?

BFC的定义

BFC全称是Block Formatting Context,即块级格式化上下文。它是一个独立的布局环境,容器里面的子元素不会影响到外面的元素,反之亦然。

BFC的作用

  • 解决margin塌陷。

eg:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<style>
    * {
        margin: 0;
        padding: 0;
    }

    section {
        width: 250px;
        height: 250px;
        background: red;

        /* 此时发生了margin塌陷 */
        margin: 50px;
    }

    .box {
        /* 触发BFC */
        overflow: hidden;
    }
</style>

<body>
    <!-- <section>section1</section> -->
    <div class="box">
        <section>section1</section>
    </div>
    <section>section2</section>
</body>
</html>
  • 清除浮动。

eg:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<style>
    * {
        margin: 0;
        padding: 0;
    }

    section {
        width: 250px;
        height: 250px;
        background: red;
        
        /* 使用display: inline-block;时候一定要加上,防止子盒子挡住父盒子,看不清楚 */
        margin: 25px;
    }

    .box {
        /* 触发BFC */
        overflow: hidden;
        
        background: black;
    }

    /* 由于容器不设高度、子元素浮动,此时容器不能被内容撑开内容会溢出到容器外面、颜色不显示 */
    .left {
        float: left;
    }
    .right {
        float: right;
    }
</style>

<body>
    <div class="box">
        <section class="left">left</section>
        <section class="right">right</section>
    </div>
</body>
</html>

那我们怎么来触发BFC呢?

如何触发BFC

  • overflow值不为visible,为hidden、auto、scroll。
  • display的值为inline-block、table、inline-table、table-cell、table-caption、flex、inline-flex、grid、inline-grid。

面试技巧:
display: inline-block;面试时候说,开发时候不用。

  • position的值为absolute、fixed。