Block Formatting Context

在 W3C CSS 2.1 标准中,BFC(block formatting context,块级格式化范围)规定了浏览器如何渲染块级元素及其浮动。具体来说,对下面这些元素将创建一个 BFC:

  • float 值不为 none 的元素
  • overflow 值不为 visible 的元素
  • position 值为 absolute 或 fixed 的元素
  • display 值为 inline-block,table-cell 或 table-caption 的元素

创建了 BFC 的元素,将作为一个整体来渲染,即它会框住它的子元素,使得子元素不会影响外面其它元素的布局。具体来说是 BFC 元素有如下这些特点:

  • BFC 元素不会和它的子元素产生垂直 margin 的折叠(非 BFC 元素则会)。
  • BFC 元素不会让浮动的子元素脱离它,而会增加大小以框住浮动子元素。
  • BFC 元素不会被浮动的兄弟元素覆盖(但是它的 margin 可能被覆盖)。

IE6 和 IE7 不使用 BFC,而是使用它独有的 hasLayout 属性。利用 hasLayout 也可以达到上述 BFC 元素的目标,但做法却不同,从而导致许多不兼容的问题。首先,下述这些元素默认的 hasLayout 为 true:

  • body 元素 以及严格模式中的 html 元素
  • table,tr,th 和 td 元素
  • img 元素
  • hr 元素
  • input,button,select,textarea,fieldset 和 legend 元素
  • iframe,embed,object 和 applet 元素
  • marquee 元素

在 IE6 中可以通过设置下列 CSS 属性使得元素的 hasLayout 为 true:

  • position: absolute 或者 fixed
  • float: 除了 none 的任何值
  • display: inline-block
  • 除了auto 之外的任何值
  • height: 除了auto 之外的任何值
  • zoom: 除了normal 之外的任何值
  • writing-mode: tb-rl
  • -ms-writing-mode: tb-rl

在 IE7 中还可以用如下方式来设置 hasLayout:

  • min- 任何值
  • min-height: 任何值
  • max- 除了 none 之外的任何值
  • max-height: 除了 none 之外的任何值
  • overflow: 除了 visible 的任何值
  • overflow-x 或者 overflow-y: 除了visible 之外的任何值

对于 IE6 和 IE7,最常见的做法是用 zoom:1 来设置 hasLayout,因为它没有其它副作用。

注记:在 CSS 3 中,block formatting context 称为 flow root。

参考资料:
[1] W3C CSS 2.1 - Visual formatting model #Normal flow
[2] W3C CSS 2.1 - Box model #Collapsing margins
[3] Block formatting context - CSS | MDN
[4] Block Formatting Context 能帮助我们做什么?
[5] CSS 101: Block Formatting Contexts - YUI Blog翻译
[6] 详说 Block Formatting Contexts (块级格式化上下文)
[7] KB010: 常规流( Normal flow )  - W3Help
[8] How does the CSS Block Formatting Context work?
[9] 块级格式化上下文 (block formatting contexts) 触发条件探讨
[A] hasLayout property (Internet Explorer) - msdn
[B] HasLayout Overview - msdn
[C] Internet Explorer hasLayout - hasLayout.net翻译
[D] On having layout — the concept of hasLayout in IE/Win
[E] 详解:已经被IE8抛弃的HasLayout | 青蛙国度
[F] The Internet Explorer hasLayout Property
[G] 更加直观地了解hasLayout和BFC - w3ctech
[H] hasLayout && Block Formatting Contexts
[I] 无 hasLayout 且 Block Formatting Context 的元素的表现差异
[J] A List Apart: Articles: CSS Positioning 101
[K] Understanding CSS and Floats
[L] 那些年我们一起清除过的浮动 - 云路科技
[M] 谈外margin collapsing(外边距叠加) - winter-cn - 博客园

原文地址:https://www.cnblogs.com/zoho/p/2868475.html