解决外边距重叠问题,把子元素和父元素的隔开,来达到效果
用table可以把两个元素隔开并且不占位置因为它是空的
display : table;
解决高度塌陷用clear: both;
clearfix 这个样式可以同时解决高度塌陷和外边距重叠的问题,当遇到这些问题时直接只要clearfix类
.clearfix::before, .clearfix::after{ content: ""; display: table; clear: both; }
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box1{
width: 200px;
height: 200px;
background-color: yellowgreen;
}
.box2{
width: 100px;
height: 100px;
background-color: rgb(230, 186, 43);
margin-top: 100px;
}
.clearfix::before,
.clearfix::after{
content: "";
display: table;
clear: both;
}
</style>
</head>
<body>
<div class="box1 clearfix">
<div class="box2"></div>
</div>
</body>
</html>
效果如图,可以看到子元素下移的同时,父元素没有一起向下,解决了外边距重叠的问题: