margin塌陷
什么是margin塌陷
父子元素在垂直方向的margin,父子元素是结合在一起的,他们两个的margin会取两者的最大值,正常情况下,父级元素相当于浏览器定位,子级元素相当于父级元素进行定位,但由于margin塌陷,父级相当于浏览器定位,而子级没有相对父级定位,这就是margin塌陷
例子:
<div class="father">
<div class="son"></div>
</div>
<style>
.father{
margin-top: 100px;
height: 200px;
width: 200px;
background-color: green;
}
.son{
height: 50px;
width: 50px;
margin-top: 50px;
background-color: red;
}
</style>
效果:
效果图可以看到,虽然我们给子元素设置了margin-top:50px,但是却没有效果,父子元素像粘在一起一样,他们两个的margin会取两者的最大值。
如何解决margin塌陷
触发bfc
改变父级的渲染规则有以下四种方法,给父级盒子添加()
(1)position:absolute/fixed
(2)display:inline-block;
(3)float:left/right
(4)overflow:hidden
这四种方法都能触发bfc,但是使用的时候都会带来不同的麻烦,具体使用中还需根据具体情况选择没有影响的来解决margin塌陷
margin合并
什么是margin合并
两个兄弟结构的元素在垂直方向上的margin是合并的
例子:
<div class="one"></div>
<div class="two"></div>
<style>
.one{
background-color: green;
height: 100px;
width: 100px;
margin-bottom: 100px;
}
.two{
background-color: red;
height: 100px;
width: 100px;
margin-top: 100px;
}
</style>
效果:
可以看到,正常情况下,红色div和绿色div垂直方向的间距应该是200px,但是结果只有100px,因为兄弟元素在垂直方向上的margin会合并。