Solve the problem of margin collapse

Margin collapse is also called margin merging, which refers to the margins of two adjacent block-level elements in the normal flow (sibling or parent-child relationship), combined into a single margin, but only the upper and lower margins If there is a collapse, the left and right margins will not have this problem.

The first type: father-son relationship
<div class="father1">
    <div class="son1">子元素1</div>
</div>

 .father1{
            width: 200px;
            height: 200px;
            background-color: yellow;
        }
        .son1{
            width: 150px;
            height: 150px;
            text-align: center;
            line-height: 150px;
            background-color: deepskyblue;
        }

Under normal circumstances

Add margin-top to child elements

 .son1{
            width: 150px;
            height: 150px;
            text-align: center;
            line-height: 150px;
            background-color: deepskyblue;
            margin-top: 50px;
        }

image

Comment out the margin-top of the child element, and add margin-top to the parent element

 .father1{
            width: 200px;
            height: 200px;
            background-color: yellow;
            margin-top: 50px;
        }

Insert picture description here

Add margin-top to parent element and child element, and the size is different

 .father1{
            width: 200px;
            height: 200px;
            background-color: yellow;
            margin-top: 50px;
        }
        .son1{
            width: 150px;
            height: 150px;
            text-align: center;
            line-height: 150px;
            background-color: deepskyblue;
            margin-top: 100px;
        }

image

The second type: adjacent brother relationship
<div class="father1"></div>
<div class="father2"></div>

 		.father1{
            width: 100px;
            height: 100px;
            background-color: yellow;
        }
        .father2{
            width: 100px;
            height: 100px;
            background-color: pink;
        }

image

		.father1{
            width: 100px;
            height: 100px;
            background-color: yellow;
            margin-bottom: 100px;
        }
        .father2{
            width: 100px;
            height: 100px;
            background-color: pink;
            margin-top: 50px;
        }

image

When the margins collapse, how are the margins calculated?
1. Both are positive numbers, take the larger value
2. Both are negative numbers, take the larger absolute value
3. One positive and one negative, take the sum of the two

Guess you like

Origin blog.csdn.net/pig_html/article/details/112467447