BFC模型浅识

3,140 阅读3分钟

本文多为查资料整理,如有不到之处,请指正。

1.基本概念

BFC为Block Formatting Context的简写,简称为“块级格式化上下文”,BFC为浏览器渲染某一区域的机制,CSS2.1 中只有BFC和IFC, CSS3中还增加了GFC和FFC。

2.产生条件

  • float的值不为none。
  • overflow的值为auto,scroll或hidden。

    block boxes with ‘overflow’ other than ‘visible’ (except when that value has been propagated to the viewport)
    意思是:overflow的值为auto,scroll或hidden,且这个属性没有传播到视口,何为传播到视口?详见3.2

  • display的值为table-cell, table-caption, inline-block中的任何一个。
  • position的值不为relative和static。

一点总结:display:table-cell; 是一个比较好用的属性(ie8+),跟inline-block具有相同的效果。但是我们知道,当元素inline-block后,相邻元素之间会有空隙(准确的说法详见3.3),而table-cell不会。
另外table-cell的宽度永远不会超过父元素的宽度。

3.关联产生的疑问?

1.垂直margin折叠

因为在bfc的介绍中(戳我查看),有这样一段描述,从而产生了这样的疑问,描述如下:

In a block formatting context, boxes are laid out one after the other, vertically, beginning at the top of a containing block. The vertical distance between two sibling boxes is determined by the ‘margin’ properties. Vertical margins between adjacent block-level boxes in a block formatting context collapse.

意思是:在bfc中,盒子从包含块的顶端开始垂直地一个接一个地排列,两个盒子之间的垂直的间隙是由他们的margin 值所决定的。两个相邻的块级盒子的垂直外边距会发生叠加。

那么我们在没有bfc的情况下垂直外边距也是会折叠的,这是为何?什么情况下会产生?bfc里的边距合并和普通的边距合并有什么关系?

查了下资料,有赞前端的一篇解释的很好,深入理解CSS外边距折叠

2.overflow扩散到视口的解释

我们知道bfc模型里的布局不会影响到父元素以外的边距和浮动,当在body上设置overflow:hidden后,并没有达到这种效果。戳我查看问题描述demo

英文描述是:

user agents must instead apply the 'overflow' property from the first such child element to the viewport, if the value on the root element is 'visible'. The 'visible' value when used for the viewport must be interpreted as 'auto'. The element from which the value is propagated must have a used value for 'overflow' of 'visible'.

意思是用户不要在第一个body元素上设置overflow,而要设置在viewport上,也就是视口容器root element html元素。

言外之意就是,当使用具有扩散propagate属性的时候,需要设置在viewport元素上,也就是说以html元素上的属性为准,propagate属性有

3.inline-block间隙的产生原因

<div>
  <div style="display:inline-block;"></div>
  <div style="display:inline-block;"></div>
</div>

英文单词之间会有空格,而中文没有,当将元素设为inline-block后,具有inline的属性,所有的空格、换行或回车都会被视为一个空格占位字符,于是就产生了。

解决办法

4.BFC作用

对于2栏自适应布局,3栏自适应布局很常用