BFC的作用
- contain floats(包含浮动元素) 栗子:https://jsfiddle.net/JuneDeng/uv782te3/12/
- prevent margins collapsing(阻止margin重叠) 同一个bfc里面的相连子元素,纵向的margin会发生重叠,实际的margin值是margin值较大子元素的margin值。要阻止margin重叠,只需要将它们放到不同的bfc,那么它们之间的margin就不会发生重叠了。创建新的bfc,可以阻止margin重叠。栗子:https://jsfiddle.net/JuneDeng/xhp0oyfj/9/
- prevent text wrapping(阻止文字绕排) 栗子:https://jsfiddle.net/JuneDeng/fLzjk94g/8/
如何创建BFC
float
值不为none
position
为absolute
或者fixed
display
为inline-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
- 块级元素设置了
overflow
的值,不为默认的visible
display:flow-root
,没有副作用的创建BFC,但是浏览器兼容不好content
:layout
,content
,strict
兼容性不强- flex items(
display:flex
或者inline-flex
的直接子元素) - grid items(
display:grid
或者inline-grid
的直接子元素) - multicol containers(
column-count
或者column-width
不为auto
,包括column-count: 1
) 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.