使用margin定义块元素的垂直外边距时,可能会出现外边距的合并。
1、嵌套块元素垂直外边距的塌陷
对于两个嵌套关系(父子关系)的块元素,父元素有上外边距同时子元素也有上外边距,此时父元素会塌陷较大的外边距值。
如图:
上面这种情况就属于塌陷 ---------->塌陷代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.father {
width: 600px;
height: 400px;
background-color: pink;
margin-top: 50px;
}
.son {
width: 200px;
height: 200px;
background-color: purple;
margin-top: 150px;
}
</style>
</head>
<body>
<div class="father">
<div class="son">
</div>
</div>
</body>
</html>
解决方案 :
-
可以为父元素定义上边框。
-
可以为父元素定义内边距。(这个与上面第一种解决方案类似,可以相当于给儿子添加一个外边距(个人理解))
-
可以为父元素添加overflow:hidden。------- 推荐这种
还有其他解决方式,比如浮动、固定、绝对定位的盒子不会有塌陷问题,后面总结。
看一下解决后的代码和图示:
这段代码我们采用方案1去解决
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.father {
width: 600px;
height: 400px;
background-color: pink;
margin-top: 50px;
border: 1px solid transparent;
}
.son {
width: 200px;
height: 200px;
background-color: purple;
margin-top: 150px;
}
</style>
</head>
<body>
<div class="father">
<div class="son">
</div>
</div>
</body>
</html>