CSS - Margin Merging

1. Margin merge

When two adjacent block elements meet, if the upper element has a lower margin margin-bottom and the lower element has an upper margin margin-top, the vertical spacing between them is not margin-bottom and margin-top. the sum, but the greater of the two. This phenomenon is known as the merging of the vertical margins of adjacent block elements (also known as margin collapse)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
    div {
        width: 300px;
        height: 200px;
        background-color: purple;
    }
    .xiongda {
        margin-bottom: 100px;
    }
    .xionger {
        background-color: pink;
        margin-top: 150px;  /*最终两个盒子的距离是  最大的那个为准  150*/
    }
    </style>
</head>
<body>
    <div class="xiongda">1</div>
    <div class="xionger">2</div>
</body>
</html>

Solution: Avoid.

2. Merging of vertical margins of nested block elements

For two nested block elements, if the parent element has no top padding or border, the top margin of the parent element will be merged with the top margin of the child element, and the combined margin will be the smaller of the two. The larger one, the merging will happen even if the parent element's top margin is 0.

solution:

  1. A 1 pixel top border or top padding can be defined for the parent element.
  2. You can add overflow:hidden to the parent element.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325977481&siteId=291194637