The full name of the BFC is Block Formatting Context.
BFC provides a layout environment in which the desired layout is achieved by following certain rules. The purpose is to form a separate space so that the layout of the elements inside the container does not affect the layout of the elements outside
Float elements do not go beyond the container area after the BFC is created
4 common ways to trigger a BFC (MDN includes many more)
float
Don’t fornone
position
Don’t forrelative
和static
overflow
为auto
.scroll
.hidden
display
为table-cell
.inline-block
.grid
.inline-grid
.flex
.inline-flex
display
为flow-root
Create a BFC with no side effectscontain
为layout
.content
.strict
.paint
MDN description
Sibling elements
<body>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</body>
Copy the code
.box {
height: 50px;
background-color: #009AD6;
margin: 10px 0;
}
Copy the code
Look at the margin of the second box. The spacing between the three boxes should be 20px, but in fact it is 10px. The vertical direction of the sibling element is maximized as the final spacing, not the sum (but we expected the sum).
This is the margin overlap problem caused by not triggering the BFC
The solution
- To the middle of the
div
The outer add adiv
, and set theoverflow: hidden;
oroverflow: auto;
, triggers the BFC,Form an independent space(mentioned at the beginning), so the second.box
Wrapped in a container that triggers the BFC, it will not affect the outside.box
了
<div class="box"></div>
<div style="overflow: auto;">
<div class="box"></div>
</div>
<div class="box"></div>
Copy the code
Although the BFC is triggered to achieve the desired effect, this unnecessary DOM element nesting is very bad, so in the actual development process will use margin-top and padding to achieve the desired effect
Sleepy today, tomorrow to write –2020-12-12 22:22:00
Want to think or continue to write…………
Father and son elements
<div class="parent">
<div style="margin-top: 10px;">123</div>
</div>
Copy the code
.parent {
height: 150px;
background-color: #009FFF;
margin-top: 10px; // This line of code is written or not written, see the same effect}Copy the code
I’ll record a GIF to show you
The solution
Trigger the BFC for the parent element as mentioned above, perfect solution
You can also set the parent element to padding-top: 1px to solve this problem, but it will cause unnecessary distance problems
You can also set the parent element to be a pseudo-element
.top-re::before {
content: ' ';
display: table;
}
Copy the code
What problem does the BFC solve
- The parent of the floating element has fallen in height
- Two column adaptive layout
- The margins coincide vertically
- The child element
margin-top
It affects the parent element