BFC全称Block Formatting Context ,直译“块级格式化上下文”,也有译做“块级格式化范围”。它是 W3C CSS 2.1 规范中的一个概念,它决定了元素如何对其内容进行定位,以及与其余元素的关系和相互做用。通俗的讲,就是一个div内部,咱们用float和margin布局元素。css
1.自适应布局html
<style> body { width: 300px; position: relative; } .aside { width: 100px; height: 150px; float: left; background: #f66; } .main { height: 200px; background: #fcc; } </style> <body> <div class="aside"></div> <div class="main"></div> </body>
根据BFC
布局规则第3条:ide
每一个元素的margin box的左边, 与包含块border box的左边相接触(对于从左往右的格式化,不然相反)。即便存在浮动也是如此。wordpress
所以,虽然存在浮动的元素aslide,但main的左边依然会与包含块的左边相接触。布局
根据BFC
布局规则第四条:post
BFC
的区域不会与float box
重叠。flex
咱们能够经过经过触发main生成BFC
, 来实现自适应两栏布局。spa
当触发main生成BFC
后,这个新的BFC
不会与浮动的aside重叠。所以会根据包含块的宽度,和aside的宽度,自动变窄。效果以下:3d
2.清除内部浮动code
<style> .par { border: 5px solid #fcc; width: 300px; } .child { border: 5px solid #f66; width:100px; height: 100px; float: left; } </style> <body> <div class="par"> <div class="child"></div> <div class="child"></div> </div> </body>
页面效果:
根据BFC
布局规则第六条:
计算
BFC
的高度时,浮动元素也参与计算
为达到清除内部浮动,咱们能够触发par生成BFC
,那么par在计算高度时,par内部的浮动元素child也会参与计算。
代码:
.par { overflow: hidden; }
效果以下:
<style> p { color: #f55; background: #fcc; width: 200px; line-height: 100px; text-align:center; margin: 100px; } </style> <body> <p>Haha</p> <p>Hehe</p> </body>
页面效果:
两个p之间的距离为100px,发送了margin重叠。
根据BFC布局规则第二条:
Box
垂直方向的距离由margin决定。属于同一个BFC
的两个相邻Box
的margin会发生重叠
咱们能够在p外面包裹一层容器,并触发该容器生成一个BFC
。那么两个P便不属于同一个BFC
,就不会发生margin重叠了。
代码:
<style> .wrap { overflow: hidden; } p { color: #f55; background: #fcc; width: 200px; line-height: 100px; text-align:center; margin: 100px; } </style> <body> <p>Haha</p> <div class="wrap"> <p>Hehe</p> </div> </body>
效果以下:
BFC
就是页面上的一个隔离的独立容器,容器里面的子元素不会影响到外面的元素。反之也如此。
由于BFC
内部的元素和外部的元素绝对不会互相影响,所以, 当BFC
外部存在浮动时,它不该该影响BFC
内部Box的布局,BFC
会经过变窄,而不与浮动有重叠。一样的,当BFC
内部有浮动时,为了避免影响外部元素的布局,BFC
计算高度时会包括浮动的高度。避免margin重叠也是这样的一个道理。
摘抄自:
http://www.cnblogs.com/lhb25/p/inside-block-formatting-ontext.html
参考文章:
http://www.zhangxinxu.com/wordpress/2015/02/css-deep-understand-flow-bfc-column-two-auto-layout/
http://www.w3cplus.com/css/understanding-bfc-and-margin-collapse.html
http://cssor.com/css-bfc-block-formatting-context.html