BFC (Block Formatting Contexts)

MDN document: Block formatting context

To put it simply: a BFC is a independently rendered area of the page that contains all elements inside the page, and the rendering of elements inside the area does not affect elements outside the area.

In the MDN, you can create a BFC in the following ways

Common application

Remove the floating

The sample code

<style>
  .wrap {
    border: 1px solid green;
  }
  .item {
    float: left;
    width: 100px;
    height: 100px;
    background-color: skyblue;
    margin: 0 5px;
  }
</style>

<div class="wrap">
  <div class="item"></div>
  <div class="item"></div>
</div>
Copy the code

As shown in the figure below, the parent element wrap does not wrap the child element item very well

You can take advantage of the block formatting context feature to make the parent element a block formatting context, which automatically wraps the child elements. Add overflow style to wrap

.wrap {
  border: 1px solid green;
  overflow: auto;
}
Copy the code

Results the following

Solve the floating occlusion problem

The sample code

<style>
  .box {
    width: 100px;
    aspect-ratio: 1 / 1;
    background-color: red;
  }
  .float {
    width: 50px;
    aspect-ratio: 1 / 1;
    background-color: skyblue;
    float: left;
  }
</style>

<div class="float"></div>
<div class="box"></div>
Copy the code

As shown in the figure above, the box element is obscured by the float element. You can make the box element a block formatting context without affecting the display of the float element

.box {
  width: 100px;
  aspect-ratio: 1 / 1;
  background-color: red;
  overflow: auto;
}
Copy the code

Results the following

Margin vertical overlap problem

The sample code

<style>
  .wrap {
    border: 1px solid greenyellow;
    width: 100px;
  }
  .item {
    width: 100%;
    height: 100px;
    margin: 10px 0;
    background-color: skyblue;
  }
</style>
<div class="wrap">
  <p class="item"></p>
  <p class="item"></p>
</div>
Copy the code

As shown in the figure above, margins between adjacent item elements overlap, and only one of them is computed and rendered (generally taking the larger value between them). To render margins between adjacent elements as intended, add a block formatting context to the outer layer of one of the elements.

<style>
  .wrap {
    border: 1px solid greenyellow;
    width: 100px;
  }
  .item {
    width: 100%;
    height: 100px;
    margin: 10px 0;
    background-color: skyblue;
  }
</style>
<div class="wrap">
  <p class="item"></p>
  <! -- Add a block formatting context to avoid margin overlay -->
  <div style="overflow: auto;">
    <p class="item"></p>
  </div>
</div>
Copy the code

It should look like this