First of all, let’s look at three cases of margin collapse:

1. When two adjacent block-level elements meet, the upper element has a margin-bottom margin and the lower element has a margin-top margin, then the vertical distance between them is the greater of the two values.

<style>
  .box1 {
     width: 150px;
     height: 100px;
     margin-bottom: 20px;
     background-color: rgb(201, 239, 98);
  }
  .box2 {
     width: 100px;
     height: 100px;
     background-color: rebeccapurple;
     margin-top: 10px;
  }
</style>
   <div class="box1"></div>
   <div class="box2"></div>
Copy the code

The vertical distance between the two boxes is not 30px, but 20px.

Solutions:

Try to add margins to only one box

2. For two nested block elements, if the parent element has no upper margin and border, the upper margin of the parent element will be merged with the upper margin of the child element, and the merged margin will be the larger of the two.

<style>
        .box1 {
            width: 150px;
            height: 100px;
            margin-top: 20px; 
            /* border: 1px solid #000000; */
            background-color: red;
        }
 
        .box2 {
            width: 100px;
            height: 100px;
            /* border: 1px solid #000000; */
            background-color: rebeccapurple;
            margin-top: 10px;
        }
    </style>
</head>
 
<body>
    <div class="box1">
        <div class="box2"></div>
    </div>
</body>
Copy the code

The two boxes will merge with a top margin of 20px.

Solutions:

① Define a border around the parent element

② Define an inner margin for the parent element

③ Add overflow: hidden to parent element;

④ Adding a float

⑤ Add absolute positioning

3. If there is an empty block-level element, such as border, padding, inline content, height, and min-height, then there is no barrier between the top and bottom margins, and the top and bottom margins are merged.

<p style="margin-bottom: 0px;" "> <div style="margin-top: 20px; margin-bottom: 20px;" ></div> <p style="margin-top: 0px;" > The distance between this paragraph and the above paragraph will be 20px</p>Copy the code

It can be understood that the width of the middle div is 0 and the distance between the top and bottom is fused. Only the maximum value of the margin is taken.