El colapso de márgenes también se denomina fusión de márgenes, que se refiere a los márgenes de dos elementos adyacentes a nivel de bloque en el flujo normal (relación de hermanos o padre-hijo), combinados en un solo margen, pero solo los márgenes superior e inferior Si hay un colapso, este problema no ocurrirá en los márgenes izquierdo y derecho.
El primer tipo: relación padre-hijo.
<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;
}
Agregar margen superior a los elementos secundarios
.son1{
width: 150px;
height: 150px;
text-align: center;
line-height: 150px;
background-color: deepskyblue;
margin-top: 50px;
}
Comente el margin-top del elemento secundario, agregue margin-top al elemento principal
.father1{
width: 200px;
height: 200px;
background-color: yellow;
margin-top: 50px;
}
Agregue margin-top al elemento principal y al elemento secundario, y el tamaño es diferente
.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;
}
El segundo tipo: relación de hermano adyacente
<div class="father1"></div>
<div class="father2"></div>
.father1{
width: 100px;
height: 100px;
background-color: yellow;
}
.father2{
width: 100px;
height: 100px;
background-color: pink;
}
.father1{
width: 100px;
height: 100px;
background-color: yellow;
margin-bottom: 100px;
}
.father2{
width: 100px;
height: 100px;
background-color: pink;
margin-top: 50px;
}
Cuando los márgenes se contraen, ¿cómo se calculan los márgenes?
1. Ambos son números positivos, toma el valor mayor
2. Ambos son números negativos, toma el valor absoluto mayor
3. Uno positivo y uno negativo, toma la suma de los dos