网上有很多帖子是说bfc的,但是大部分都是讲一些,具体的表现,很少有涉及到原理的,我结合自己的理解和大家一起分享下BFC的原理。
BFC是Block Formatting Context的简写,中文直译为块级格式上下文。
BFC就是一种布局方式,其中Formatting context 是W3C CSS2.1规范中的一个概念,他是页面中的一块渲染区域,并且有一套的渲染规则,他决定了其子元素如何定位,以及和其他元素的关系和相互作用。最常见的Formatting context有Block Formatting Context和Inline Formatting Context.
通俗一点,可以把BFC理解为一个封闭的大箱子,箱子内部的元素无论如何翻江倒海,都不会影响到外部。
触发BFC的方式(一下任意一条就可以)
1.float不为none;
2.overflow不为visibile
3.display:table-cell、table-caption、inline-block
4.posttion不为static、relative
BFC常见的四种情况
1.浮动的元素会被父级计算高度,即清除内部浮动(父级触发了BFC)
2.非浮动元素不会覆盖浮动元素位置,即创建自适应两栏布局(非浮动元素触发了BFC)
3.margin不会传递给父级,即父子不齐下(父级触发了BFC)
4.两个相邻元素上下margin会重叠,即垂直margin合并(给其中一个元素增加一个父级,然后让他的父级触发BFC)
<div style="border:1px solid #f00;overflow:hidden; ">
<div style="width:100px; height:100px; background:lightgreen;float:left;">bfc</div>
</div>
<div style="border:1px solid #f00;margin-top:100px; ">
<div style="width:100px; height:100px; background:lightgreen;float:left;">bfc1</div>
<div style="width:100px; height:100px; background:yellow;overflow:hidden;">bfc2</div>
</div>
<div style="background:blue;margin-top:100px;overflow:hidden;">
<div style="width:100px; height:100px; background:lightgreen; margin-top:100px;">bfc1</div>
<div style=" height:100px; background:yellow;">111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111</div>
</div>
<div style="margin-top:100px; border:1px solid yellow;">
<div style="width:100px; height:100px; background:lightgreen; margin:100px 0;">bfc1</div>
<div style="overflow:hidden;">
<div style="width:100px; height:100px; background:yellow; margin:100px 0;">bfc2</div>
</div>
</div>