- 在讨论BFC的特点之前,先得了解一下边距重叠问题。
- 父子元素边距重叠:当父元素为非BFC时,第一个子元素的margin-top会重叠到父元素的margin-top。
<section>
<style>
#bfc3{
background-color:deeppink;
height: 50px;
}
#bfc4{
height: 50px;
background-color: darksalmon;
margin-top: 0px;
width: 400px;
}
</style>
<div id="bfc3">
<div id="bfc4">
<p>父子重叠</p>
</div>
</div>
</section>
效果:
- 兄弟元素边距重叠:当两个相邻的元素为非BFC时,前者的margin-bottom和后者的margin-top会重叠。
- 空元素边距重叠:当空元素设置了margin-top和margin-bottom时,两个margin会重叠。
- BFC的概念
Formatting Context:指页面中的一个渲染区域,并且拥有一套渲染规则,他决定了其子元素如何定位,以及与其他元素的相互关系和作用。
BFC:块级格式化上下文,它是指一个独立的块级渲染区域,只有Block-level BOX参与,该区域拥有一套渲染规则来约束块级盒子的布局,且与区域外部无关。 - BFC的原理
- BFC区域的元素不会影响外面的元素,反之亦然。
- BFC区域不会与float元素发生重叠
- 计算BFC高度时,浮动元素能够撑开BFC的高度,达到清除浮动的效果。
<section>
<style>
#bfc1{
background-color:deeppink;
overflow: auto;
}
#bfc2{
height: 50px;
background-color: darksalmon;
margin-top: 30px;
float: left;
width: 400px;
}
</style>
<div id="bfc1">
<div id="bfc2">
<p>浮动元素能够撑开父元素的高度</p>
</div>
</div>
</section>
效果:父元素高度被浮动元素撑开
- 根据BFC的原理,可以解决边距重叠问题,当不想让两个元素相互影响时,可以对两个元素创建BFC,这样就不会发生边距重叠的问题。对于父子元素边距重叠问题,只需对父元素创建BFC,则可解决父子重叠。
- 如何创建BFC
- overflow 除了 visible 以外的值 (hidden、auto、scroll)
- 设置float不为none
- 设置position不为relative和static(absolute,fixed,sticky)
- 设置display为table-cell,flex,inline-block