bfc

BFC的作用

  1. contain floats(包含浮动元素) 栗子:https://jsfiddle.net/JuneDeng/uv782te3/12/
  2. prevent margins collapsing(阻止margin重叠) 同一个bfc里面的相连子元素,纵向的margin会发生重叠,实际的margin值是margin值较大子元素的margin值。要阻止margin重叠,只需要将它们放到不同的bfc,那么它们之间的margin就不会发生重叠了。创建新的bfc,可以阻止margin重叠。栗子:https://jsfiddle.net/JuneDeng/xhp0oyfj/9/
  3. prevent text wrapping(阻止文字绕排) 栗子:https://jsfiddle.net/JuneDeng/fLzjk94g/8/

如何创建BFC

  1. float 值不为 none
  2. positionabsolute或者fixed
  3. displayinline-block,table-cell,table-caption,table,table-row,table-row-group,table-header-group,table-footer-group (which is the default for HTML tables, table rows, table bodies, table headers and table footers, respectively),inline-table
  4. 块级元素设置了overflow的值,不为默认的visible
  5. display:flow-root,没有副作用的创建BFC,但是浏览器兼容不好
  6. content:layout,content,strict 兼容性不强
  7. flex items(display:flex或者inline-flex的直接子元素)
  8. grid items(display:grid或者inline-grid的直接子元素)
  9. multicol containers(column-count或者column-width不为auto,包括column-count: 1)
  10. column-span: all

总结

A block formatting context contains everything inside of the element creating it.

Block formatting contexts are important for the positioning and clearing of floats. The rules for positioning and clearing of floats apply only to things within the same block formatting context. Floats do not affect the layout of the content inside other block formatting contexts, and clear only clears past floats in the same block formatting context. Margin collapsing also occurs only between blocks that belong to the same block formatting context.

reference

  1. https://www.smashingmagazine.com/2017/12/understanding-css-layout-block-formatting-context/
  2. https://www.sitepoint.com/understanding-block-formatting-contexts-in-css/
  3. https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Block_formatting_context