[1]相邻块元素垂直外边距的合并
1.当上下相邻的二个块元素相遇时,如果上面的元素有下外边距margin-buttom
2.下面的元素有上外边距margin-top,则他们之间的垂直间距不是margin-bottom与mtop之和
3.取二者值中的较大者的这种现象称之为相邻块元素垂直外边距的合并
解决方法:
尽量只给一个盒子加margin
<style>
.a1{
width: 200px;
height: 200px;
background-color: aquamarine;
margin-bottom: 100px;
}
.a2{
margin-top: 50px;
width: 200px;
height: 200px;
background-color: darkorange;
}
</style>
</head>
<body>
<div class="a1"></div>
<div class="a2"></div>
</body>
运行结果:
【2】嵌套块元素垂直外边距的合并
1、对于二个嵌套关系的块元素,如果父元素没有上内边距或边框
2、父元素的上外边距会与子元素的上外边距发生合并
3、合并值为二者中的较大者
解决方法:
1、可以给父元素定义上边框border-top
2、可以给父元素定义上内边距padding-top
3、可以给父元素添加overflow:hidden;
4、转为行内块元素
5、设置浮动
其他:浮动、固定、绝对定位的盒子
<style>
.father{
width: 300px;
height: 300px;
background-color: aquamarine;
margin-top: 100px;
/* border: 1px solid; */
/* padding: 1px; */
overflow: hidden;
}
.son{
margin-top: 150px;
width: 100px;
height: 100px;
background-color: blue;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
外边距塌陷的运行结果:
不管是子盒子还是父盒子
都会被往下顶;
子盒子设置了margin-top=100px,会把父盒子往下顶100px,即:坑爹行为
如果父亲设置了margin-top=200px,则父盒子会往下移动200px
消除塌陷后运行结果: