What is BFC?

BFC: block formatting Context

Understanding: BFC elements can be understood as isolated intervals (children of the BFC do not affect external elements);

Ii. How to trigger BFC?

How to make an element become a BFC is triggered by the following rules:

  • float:left | right

  • overflow:hidden | scroll | auto; (Not visible)

  • display:inline-block | table-cell | table-caption | flex | grid ; (non-none, non-inline, non-block)

  • position: absolute | fiexed ; (relative)

3. What problems can BFC solve?

BFC can solve:

  • Margin overlap problem
  • Margin collapse problem
  • Height collapse problem

Margin overlap problem

.div1 {
  margin-bottom: 20px;
  width: 100px;
  height: 100px;
  background-color: red;
}
.div2 {
  margin-top: 20px;
  width: 100px;
  height: 100px;
  background-color: blue;
}

<div class="div1"></div>
<div class="div1"></div>
Copy the code

The margin of the two divs overlaps:

Solution:

<! 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, Container {overflow: hidden; /> <title>BFC</title> <style> // change it to BFC}. Div1 {margin-bottom: 20px; width: 100px; height: 100px; background-color: red; } .div2 { margin-top: 20px; width: 100px; height: 100px; background-color: blue; } </style> </head> <body> <div class="container"> <div class="div1"></div> </div> <div class="container"> <div class="div2"></div> </div> </body> </html>Copy the code

Margin collapse problem

 .box {
   width: 100px;
   height: 100px;
   background-color: pink;
 }
.box1 {
  width: 40px;
  height: 40px;
  margin-top: 50px;
  background-color: lightgreen;
}

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

Error: parent element margin-top:50px, child element has no margin-top, causing margin collapse

Solution:

According to the trigger rule, make box a BFC element, add Overflow: Hidden or something else

.box {
   width: 100px;
   height: 100px;
   overflow: hidden;
   /* float: left; */
   /* display: flex; */
   background-color: pink;
 }
Copy the code

Height collapse problem

.father {
  width: 100px;
  background-color: lightseagreen;
}
.child1{
  width: 40px;
  height: 40px;
  float: left;
  background-color: red;
}
.child2{
  width: 40px;
  height: 40px;
  float: left;
  background-color: pink;
}

<div class="father">
  <div class="child1"></div>
  <div class="child2"></div>
</div>
Copy the code

The problem with the above code: the parent element has no height

Solution: Make the parent element BFC (add Overflow: Hidden, etc.)

 .father {
   width: 100px;
   overflow: hidden;
   background-color: lightseagreen;
 }
Copy the code