BFC渲染规则

BFC:Block formatting context,官网上的定义是这样的:

Floats, absolutely positioned elements, block containers (such as inline-blocks, table-cells, and table-captions) that are not block boxes, and block boxes with ‘overflow’ other than ‘visible’ (except when that value has been propagated to the viewport) establish new block formatting contexts for their contents.
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中,在竖直方向上,子元素代表的盒子自包含块顶部依次排列。两个盒子之间的垂直的间隙是由他们的 margin 值所决定的,两个相邻的块级盒子的垂直外边距会发生融合(叠加);在水平方向上,每一个盒子的左外边缘(margin-left)会触碰到容器的左边缘(border-left)(对于从右到左的格式来说,则触碰到右边缘),即使存在浮动也是如此,除非这个盒子创建一个新的块级格式化上下文。

应用了BFC的盒子就是一个独立的盒子,它规定了内部的 block-level box 如何布局,并且这个独立盒子里的布局不受外部影响,也不会影响到外面的元素。

如何触发BFC?

  1. 浮动元素,float 除 none 以外的值
  2. 绝对定位元素,position(absolute,fixed)
  3. 非块级盒子的块级容器,例如:inline-blocks, table-cells, and table-captions。
  4. overflow 值不为 visible 的块级盒子。

由于浮动元素与绝对定位元素脱离文档流,会对页面其他元素的布局产生影响,所以我们最好通过设置overflow:hidden的方式触发BFC

ps

块级盒子:每个块级元素(display属性值为block,table,list-item)生成一个主要的块级盒(Principal Block-level Box)来包含其后代盒和生成的内容。同时参与定位体系 Positioning Scheme 。某些块级元素还会在主要盒之外产生额外的盒: list-item 元素。这些额外的盒会相对于主要盒来摆放。

具体参考链接:https://segmentfault.com/a/1190000003096320https://developer.mozilla.org/en-US/docs/Web/CSS/Visual_formatting_model包含块

  BFC应用

解决margin重叠问题: 垂直相邻的两个外边距中较小的一个会被较大的一个合并。

例如,两个p 元素之间的 margin 为 50px,此时发生了外边距叠加。要解决这个叠加问题,即让每个 p 元素之间的 margin 是 100px,应该怎么办?我们可以给 每个p 元素添加一个父元素,让并它触发 BFC。

清除 float 浮动,解决高度坍塌

与position:absolute、position:relative元素在BFC中不占有位置不同,float元素在BFC中其实是实际占有空间的。

实现特殊布局,如两栏布局与三栏布局

参考文档:

https://www.w3.org/TR/CSS21/visuren.html#inline-formatting

https://www.sitepoint.com/understanding-block-formatting-contexts-in-css/

https://developer.mozilla.org/zh-CN/docs/Web/CSS/CSS_Box_Model

https://blog.duan-ya.com/article/2017-01-22/132

posted @ 2017-07-28 11:38  月上柳梢头,  Views(209)  Comments(0)    收藏  举报