1、BFC是什么?css
在解释 BFC 是什么以前,须要先介绍 Box、Formatting Context的概念。html
Box 是 CSS 布局的对象和基本单位, 直观点来讲,就是一个页面是由不少个 Box 组成的。元素的类型和 display 属性,决定了这个 Box 的类型。 不一样类型的 Box, 会参与不一样的 Formatting Context(一个决定如何渲染文档的容器),所以Box内的元素会以不一样的方式渲染。让咱们看看有哪些盒子:css3
Formatting context 是 W3C CSS2.1 规范中的一个概念。它是页面中的一块渲染区域,而且有一套渲染规则,它决定了其子元素将如何定位,以及和其余元素的关系和相互做用。最多见的 Formatting context 有 Block fomatting context (简称BFC)和 Inline formatting context (简称IFC)。ide
CSS2.1 中只有 BFC
和 IFC
, CSS3 中还增长了 GFC
和 FFC。
布局
BFC(Block formatting context)直译为"块级格式化上下文"。它是一个独立的渲染区域,只有Block-level box参与, 它规定了内部的Block-level Box如何布局,而且与这个区域外部绝不相干。flex
2、触发BFC(方法不少,适应于不一样的场景)spa
3、应用3d
一、清楚浮动(第6条规则)code
<style type="text/css"> .father{ border: 2px solid green; } .son{ width: 100px; height: 100px; border: 2px solid red; float: left; } </style> <body> <div class="father"> <div class="son"></div> <div class="son"></div> </div>
显而易见,子元素的浮动致使父元素坍塌!以下图:
<style type="text/css"> .father{ border: 2px solid green; overflow: hidden; //触发父元素的BFC清除浮动; } .son{ width: 100px; height: 100px; border: 2px solid red; float: left; } </style> <body> <div class="father"> <div class="son"></div> <div class="son"></div> </div>
二、自适应两栏布局(第三、4条规则)orm
<style type="text/css"> .aside{ width: 100px; height: 150px; float: left; background-color: green; } .main{ height: 200px; background-color: red; } </style> <body> <div class="aside"></div> <div class="main"></div>
第3条。
<style type="text/css"> .aside{ width: 100px; height: 150px; float: left; background-color: green; } .main{ overflow: hidden;//第4条 也很明显的体现了第5条 height: 200px; background-color: red; } </style> <body> <div class="aside"></div> <div class="main"></div>
3、防止margin垂直合并(第2条)
<style type="text/css"> .box{ width: 100px; height: 100px; background-color: green; margin: 100px; } </style> <body> <div class="box"></div> <div class="box"></div>
//同一个BFC内垂直margin重叠
<style type="text/css"> .box{ width: 100px; height: 100px; background-color: green; margin: 100px; } .wraper{ overflow: hidden; } </style> <body> <div class="box"></div> <div class="wraper"> //给下面的box添加一个wraper并触发其BFC,如今两个BFC互不影响。 <div class="box"></div> </div>
注:(引自jizhula.com)