什么叫边距重叠
外边距重叠是指两个或者多个盒子(相邻或者嵌套)的相邻边界重合在一起,margin全部为正值,取最大;一正一负相加;没有正值则取绝对值最大,之后用0减去这个值
父子边距重叠
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{
margin:0;
padding:0;
}
.parent{
height:200px;
background: #88f;
}
.child{
margin-top: 20px;
padding: 1px;
height:100px;
background-color: #0ff;
width:200px;
}
</style>
</head>
<body>
<!-- 父子盒子嵌套 -->
<div class="parent">
<div class="child"></div>
</div>
</body>
</html>
解决这种现象的出现是因为内外边距重叠了,解决方法如下:
- 为parent类加 overflow:hidden
- 为parent类加padding-top:20px;box-sizing: border-box;
删除child类上的margin-top:20px - 为parent类加 position: relative;
为child类加position:absolute - 为child类加display: inline-block;
- 为child类加float: left;
- 将子元素的margin-top:20px改为border:20px solid 父元素颜色
使用上述6种方法均能实现下面效果:
相邻边距重叠
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{
margin:0;
padding:0;
}
.sibling1{
background-color: red;
height: 200px;
width: 100%;
margin-bottom: 50px;
}
.sibling2{
background-color: green;
height: 100px;
margin-top: 20px;
}
</style>
</head>
<body>
<div class="sibling1"></div>
<div class="sibling2"></div>
</body>
</html>
解决相邻边距重叠的方式:
- 为其中一个添加display:inline-block
- 为其中一个添加父元素,并为父元素添加overflow:hidden属性,代码如下所示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{
margin:0;
padding:0;
}
.sibling1{
background-color: red;
height: 200px;
width: 100%;
margin-bottom: 50px;
}
.sibling2{
background-color: green;
height: 100px;
margin-top: 20px;
}
.father{
overflow: hidden;
}
</style>
</head>
<body>
<div class="father">
<div class="sibling1"></div>
</div>
<div class="sibling2"></div>
</body>
</html>
使用上述2种方法均能实现下面效果: