一、什么是外边距塌陷
使用margin定义块元素的垂直外边距时,可能会出现外边距的合并。
(1) 相邻块元素垂直外边距的合并
1.当上下相邻的两个块元素相遇时,如果上面的元素有下外边距margin-bottom 2.下面的元素有上外边距margin-top,则他们之间的垂直间距不是margin-bottom与margin-top之和 3.取两个值中的较大者**这种现象被称为相邻块元素垂直外边距的合并(也称外边距塌陷)。
解决方案:
尽量给只给一个盒子添加margin值
代码演示:
<style>
.top,
.bottom {
width: 200px;
height: 200px;
background-color: pink;
}
.top {
margin-bottom: 100px;
}
.bottom {
background-color: purple;
margin-top: 50px;
}
</style>
<body>
<div class="top"></div>
<div class="bottom"></div>
</body>
(2)嵌套块元素垂直外边距的合并(塌陷)
1.对于两个嵌套关系的块元素,如果父元素没有上内边距及边框 2.父元素的上外边距会与子元素的上外边距发生合并 3.合并后的外边距为两者中的较大者
解决方案 :
1. 可以为父元素定义上边框。 2. 可以为父元素定义上内边距 3. 可以为父元素添加overflow:hidden。
还有其他方法,比如浮动、固定、绝对定位的盒子不会有问题,
代码演示:
<style>
.father {
width: 500px;
height: 500px;
background-color: pink;
/*嵌套关系 垂直外边距合并 解决方案 */
/*1. 可以为父元素定义上边框 transparent 透明*/
/*border-top: 1px solid transparent;*/
/*2. 可以给父级指定一个 上 padding值*/
/*padding-top: 1px; */
/*3. 可以为父元素添加overflow:hidden。*/
overflow: hidden;
}
.son {
width: 200px;
height: 200px;
background-color: purple;
margin-top: 100px;
}
</style>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>