1.BFC is block Formatter Context, a block-level concept in the CSS.
We all know that. If you have a pair of parent group elements, if the child elements have their original height and width and are set to float out of the document flow. The parent element will collapse in height, making the style of the element very ugly.
Let’s show you the code
<div class="fath">
<div class="son"></div>
</div>
<style>
.fath{
width: 400px;
height: 30px;
background-color: blue;
}
.son{
width: 300px;
height: 200px;
background-color: aqua;
float: left;
}
</style>
Copy the code
The figure shows that in this case, the height of the parent element does not carry the subelement.
This, then, is an important moment to demonstrate the role of the BFC.
Several important characteristics of BFC :(set for parent elements)
1. Set overflow to hidden.
2. Set the display value to inline-block
3. Position is not static or relative(i.e. absolute or fix).
4. The parent element float cannot also be None.
As you can see from the figure, if the CSS style of the parent element meets one of the above conditions, the parent element can form a stream of elements consistent with the child element, and spread out its own width and height according to the child element’s width and height.
Why is that? In the BFC box, all styles have a block-level scope that applies only to the elements inside the BFC box and has nothing to do with the outside area.
!!!!! Note: When setting the parent element to BFC, the parent element does not need to set its initial width and height.
Other functions of the BFC.
Again, a parent-child element.
body{
background-color: brown;
}
.fath{
width: 400px;
height: 400px;
background-color: blue;
}
.son{
margin-top: 20px;
width: 300px;
height: 200px;
background-color: aqua;
}
Copy the code
I want a 20px margin between the top of the child element and the top of the parent element. But you’ll find out when you write the code.
It works like this:
Obviously, in this case, the parent and child elements together create a 20px margin at the top of the browser viewport. It is also caused by margin collapse when the box is using margin.
This problem can be solved by taking one of the BFC’s features and shooting it in the parent element’s CSS.