1、 垂直外边距合并、也称外边距塌陷
- 适用场景:两个垂直排列的同级元素(上面的盒子设置margin-bottom、下面的盒子设置margin-top)
<!-- html部分 -->
<div class="fa">
<div class="son1">A盒子</div>
<div class="son2">B盒子</div>
</div>
- 解决方式:只需要设置其中的一种即可(要么保留margin-top、要么保留margin-bottom)
<!-- css部分 -->
<style type="text/css">
.fa {
width: 200px;
height: 240px;
background-color: #ccc;
margin: 20px auto;
}
.son1, .son2 {
width: 100px;
height: 100px;
}
.son1 {
background-color: pink;
/* margin-bottom: 20px; */
}
.son2 {
background-color: red;
margin-top: 40px;
}
</style>
- 页面展示:取margin-top与margin-bottom两者中值最大的那个
2、父子黏连
- 适用场景:父子元素(子元素设置margin-top、父盒子也会受到影响)
<!-- html部分 -->
<div class="fa">
<div class="son">子元素</div>
</div>
- 解决方式:
方式一:给父级元素添加overflow属性,比如:overflow: hidden; 或者 overflow: auto;
<!-- css部分 -->
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.fa {
width: 200px;
height: 240px;
background-color: #ccc;
overflow: auto;
}
.son {
width: 100px;
height: 100px;
background-color: pink;
margin-top: 40px;
}
</style>
方式二:给父级元素添加padding属性,比如:padding: 1px;
<!-- css部分 -->
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.fa {
width: 200px;
height: 240px;
background-color: #ccc;
padding: 1px;
}
.son {
width: 100px;
height: 100px;
background-color: pink;
margin-top: 40px;
}
</style>
方式三:给父级元素添加border属性,比如:border: 1px solid transparent;
<!-- css部分 -->
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.fa {
width: 200px;
height: 240px;
background-color: #ccc;
border: 1px solid transparent;
}
.son {
width: 100px;
height: 100px;
background-color: pink;
margin-top: 40px;
}
</style>
方式四:给父级元素添加position属性,比如:position: absolute;
<!-- css部分 -->
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.fa {
width: 200px;
height: 240px;
background-color: #ccc;
position: absolute;
}
.son {
width: 100px;
height: 100px;
background-color: pink;
margin-top: 40px;
}
</style>
方式五:给父级元素添加float属性,比如:float: left;
<!-- css部分 -->
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.fa {
width: 200px;
height: 240px;
background-color: #ccc;
float: left;
}
.son {
width: 100px;
height: 100px;
background-color: pink;
margin-top: 40px;
}
</style>
方式六:给父级元素添加伪元素
<!-- css部分 -->
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.fa {
width: 200px;
height: 240px;
background-color: #ccc;
}
.fa::before {
content: '';
display: table;
}
.son {
width: 100px;
height: 100px;
background-color: pink;
margin-top: 40px;
}
</style>
方式七:给父级元素添加display属性,比如:display: table;
<!-- css部分 -->
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.fa {
width: 200px;
height: 240px;
background-color: #ccc;
display: table;
}
.son {
width: 100px;
height: 100px;
background-color: pink;
margin-top: 40px;
}
</style>
- 页面展示: