BFC(Block Formatting Context)Is a CSS rendering mode for a box model layout in a Web page. It’sPositioning systemBelong toGeneral document flow.

To implement a BFC layout, one of the following conditions must be met:

1. Float is not none. 2. Position is not static or relative. Display: Inline-block, table-cell, flex, table-flex, Caption: inline-flex; overflow: Visible

There are many ways to create a BFC, but some of them may cause other problems, such as overflow: Scroll, etc., so be careful when using them. This article uses Overflow: Hidden to create a BFC.

1. The BFC area does not overlap the float box

<style>
        body {
            width: 300px;
            position: relative;
        }

        .aside {
            width: 100px;
            height: 150px;
            float: left;
            background: # 666666;
        }

        .main {
            height: 200px;
            background: #fcc;
        }
    </style>
<body>
    <div class="aside"></div>
    <div class="main"></div>
</body>

Copy the code

2. When calculating the height of the BFC, the floating element is also involved

 <style>
        body {
            width: 500px;
        }

        .par {
            border: 5px solid #fcc;/ /* overflow: hidden; */ /* display: inline-block; */ /* position: absolute; * / / *float: left; */
        }

        .child {
            border: 5px solid #f66;
            width: 100px;
            height: 100px;
            float: left;
        }

    </style>
Copy the code

In order to clear the internal float, we can trigger the PAR to generate BFC. Then when the PAR calculates the height, the floating element child inside the PAR will also participate in the calculation. So when we add overflow: Hidden to par, the problem is solved.

3. The margins of two adjacent boxes belonging to the same BFC will overlap

<style>
    p {
        color: #f55;
        background: #fcc;
        width: 200px;
        line-height: 100px;
        margin: 100px;
    }
</style>

<body>
        <p>haha</p>
        <p>hehe</p>
</body>
Copy the code

    <style>
 p {
        color: #f55;
        background: #fcc;
        width: 200px;
        line-height: 100px;
        margin: 100px;
    }
  .warp {
            overflow: hidden;
        }
    </style>
    <p>haha</p>
    <div class="warp">
        <p>hehe</p>
    </div>
Copy the code

Summarize the three characteristics of BFC

  1. The BFC area does not overlap with the float box
  2. When calculating the height of the BFC, the floating element is also involved
  3. Margins of two adjacent boxes belonging to the same BFC will overlap