BFC块级格式化上下文

BFC就是block formatting context的缩写,中文就是“块级格式化上下文”的意思。

Formatting context是W3C CSS2.1规范中的一个概念。它是页面中的一块渲染区域,并且有一套渲染规则,它决定了其子元素将如何定位,以及和其他元素的关系和相互作用。常见的FC有BFC,IFC等。

创建BFC

  1. float 除了none以外的值
  2. overflow 除了visible 以外的值(hidden,auto,scroll )
  3. display (table-cell,table-caption,inline-block, flex, inline-flex)
  4. position值为(absolute,fixed)
  5. fieldset元素

为什么需要块级格式化上下文?

1.解决margin叠加问题 三P每个p之间的距离为50px,发生了外边距叠加。
右图是添加overflow:hidden

<html>
    <div class="bfc">
        <p>helloword</p>
    </div>
    <p>helloword</p>
    <p>helloword</p>
</html>

<style>
    .bfc {
       overflow: hidden;
    }
    p {
       background: red;
       width: 100px; 
       height: 100px;
       margin: 40px;
    }
</style>

2.用于布局
左边元素脱离文档流后,右边元素的左外边距会触碰到包含块容器的左外边框的问题

没有BFC
通过overflow:hidden创建BFC

<div style="text-align: center; border: 10px solid #000">          
    <div style="float: left; width: 100px;height: 100px; background: red">            
    </div>        
    <div style="width: 150px;height: 150px; background: blue; overflow: hidden">    
    </div>        
</div>

3.用于清除浮动
没有BFC
通过overflow:hidden创建BFC

<div style="text-align: center; overflow: hidden; border: 10px solid #000">
    <div style="float: left; width: 100px;height: 100px; background: red">            
    </div>        
    <div style="float: left; width: 100px;height: 100px; background: blue;">    
    </div>     
</div>