目录
什么是外边距塌陷?
外边距合并,又称外边距塌陷。其中有兄弟元素之间的外边距合并,也有父子元素之间的外边距合并,它们是怎么出现的呢?
兄弟元素之间的外边距合并:
出现原因:一个兄弟元素设置下外边距,另一个兄弟元素设置上外边距,造成外边距塌陷。
写入这些代码,我们不难看出两个div之间外边距应该为50px。
<style>
div{
width: 200px;
height: 200px;
}
.div1{
background-color: red;
margin-bottom: 20px;
}
.div2{
background-color: blue;
margin-top: 30px;
}
</style>
<div class="div1">第一个兄弟元素</div>
<div class="div2">第二个兄弟元素</div>
打开浏览器查看,发现二者之间的边距为30px,发生了外边距塌陷。
解决方法有:
1.给一个兄弟元素设置外边距
2.给下方兄弟元素开启bfc
display:inline-block 或者 position:absolute/fixed
3.给其中一个兄弟元素设置父元素,给父元素开启BFC
overflow:hidden
父子元素之间的外边距合并 :
出现原因:给父子元素设置同一方向的外边距 。
代码:
<style>
.parent{
width: 200px;
height: 200px;
background-color: red;
margin-top: 20px;
}
.child{
width: 100px;
height: 100px;
background-color: blue;
margin-top: 10px;
}
</style>
<div class="parent">
<div class="child">子元素</div>
</div>
发生外边距塌陷:
解决方法有:
1.给父元素设置padding
2.给父元素设置border
3.给父元素开启BFC overflow:hidden/auto
什么是BFC?
全称:Block Formatting Context,即块级格式化上下文。
BFC触发条件:
1.html元素
2.float不为none
3.position为absolute fixed
4.display:inline-block
5.overflow不为visible
BFC作用:
1.避免外边距重叠
2.清除浮动
3.阻止浮动元素覆盖非浮动元素
4.两列布局 左侧顶宽 右侧自适应
5.三列布局 左右定宽 中间自适应