lihongjie0209 / myblog

4 stars 0 forks source link

CSS : BFC #241

Open lihongjie0209 opened 3 years ago

lihongjie0209 commented 3 years ago

定义

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.

In a block formatting context, each box's left outer edge touches the left edge of the containing block (for right-to-left formatting, right edges touch). This is true even in the presence of floats (although a box's line boxes may shrink due to the floats), unless the box establishes a new block formatting context (in which case the box itself may become narrower due to the floats).

首先 BFC 的定义和我们在正常文档流中的表现是一致的.

那么我们正常的文档流也是一个BFC??

根元素(<html>)
浮动元素(元素的 float 不是 none)
绝对定位元素(元素的 position 为 absolute 或 fixed)
行内块元素(元素的 display 为 inline-block)
表格单元格(元素的 display 为 table-cell,HTML表格单元格默认为该值)
表格标题(元素的 display 为 table-caption,HTML表格标题默认为该值)
匿名表格单元格元素(元素的 display 为 table、table-row、 table-row-group、table-header-group、table-footer-group(分别是HTML table、row、tbody、thead、tfoot 的默认属性)或 inline-table)
overflow 值不为 visible 的块元素
display 值为 flow-root 的元素
contain 值为 layout、content 或 paint 的元素
弹性元素(display 为 flex 或 inline-flex 元素的直接子元素)
网格元素(display 为 grid 或 inline-grid 元素的直接子元素)
多列容器(元素的 column-count 或 column-width 不为 auto,包括 column-count 为 1)
column-span 为 all 的元素始终会创建一个新的BFC,即使该元素没有包裹在一个多列容器中(标准变更,Chrome bug)。

答案还真是, 默认的html元素就是一个BFC, 如果我们学习过文档流, 那么我们对BFC中元素的表现应该是可以理解的.

lihongjie0209 commented 3 years ago

BFC 与 BFC 之间如何相互影响

最常见的一个现象就是我们在文档流中float定位一个元素, 那么这个元素和正常的文档流就不一致了, 这个现象就是BFC之间的相互影响.

首先一个问题是: 为什么 float元素会覆盖父元素?

这个其实是z-index的问题, 默认情况下z-index是按照dom元素的顺序来排列的, 一般子元素的z-index值都比父元素的高, 这时候你再给浮动元素创建了BFC, 那么这个BFC天生就比父元素的z-index高, 所以就会渲染到上层. 那么我们有没有可能修改float元素这个BFC的z-index呢, 其实是没有办法的, 这就是BFC的第二个特性, 隔离, 两个BFC之间的z-index没有任何可比性, 只有在相关的上下文中才有意义.

然后是第二个问题: html元素也是BFC, 为什么默认可以全屏, 内部的block元素可以宽度100%, 而我的float也是BFC, 为什么宽度就变为了内容的宽度

首先我们float元素的width是可以调整到100%, 默认也是视窗的宽度, 也就是说新建的BFC默认的父BFC应该是浏览器. 如果给float元素套一个父BFC, 那么你会发现float元素在父BFC中的表现完全就是一个正常文档流中的表现. 也就是说如果我们把浮动元素的父元素设置为BFC, 那么浮动元素就会撑开父元素.

float 元素默认不占据整行是为了图文排版的文字环绕效果