What is margin collapse?

Margin collapse, also known as margin merging, is when the margins of two block-level elements that are adjacent (siblings or parent-child) in normal flow are combined to form a single margin, but only the upper and lower margins collapse, not the left and right margins.

How to solve the margin collapse?

Problem: The child box sets the upper margin, the parent box collapses with the child box, and the nested block element merges vertically with the margin

<style> *{ padding: 0; margin: 0; } .father { height: 500px; width: 500px; background: rgb(184, 184, 167); } .son { width: 200px; height: 200px; background: rgb(199, 20, 20); margin-top: 100px; </style> <body> <div class="father"> <div class="son"> </div> <body>Copy the code

As shown below, this is the desired effect, but the reality is that the parent box comes down with the child box;

Solutions:

Method 1: Set an upper border of 1 pixel for the parent box, the color is the same, but the parent box will be enlarged, so the height of the parent box is reduced by 1.

.father {
      border-top: 1px solid rgb(184, 184, 167);
      height: 499px;
 }
Copy the code

Method 2: Set an upper inner margin of 1 pixel for the subbox, which will also extend the subbox, so the height of the subbox is reduced by 1.

.son {
     padding-top: 1px;
     height: 199px;
  }
Copy the code

Method 3: Parent box set Overflow: Hidden, trigger BFC, does not expand the box

.father {
      overflow: hidden;
  }
Copy the code