Open lihongjie0209 opened 3 years ago
最常见的一个现象就是我们在文档流中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 元素默认不占据整行是为了图文排版的文字环绕效果
定义
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元素就是一个BFC, 如果我们学习过文档流, 那么我们对BFC中元素的表现应该是可以理解的.