前端知识总结--BFC

Block Formatting Context,中文直译为块级格式上下文。less

1. BFC的定义布局

是 W3C CSS 2.1 规范中的一个概念,它决定了元素如何对其内容进行定位,以及与其余元素的关系和相互做用。网站

在建立了 Block Formatting Context 的元素中,其子元素会一个接一个地放置。垂直方向上他们的起点是一个包含块的顶部,两个相邻的元素之间的垂直距离取决于 ‘margin’ 特性。在 Block Formatting Context 中相邻的块级元素的垂直边距会折叠(collapse)。spa

在 Block Formatting Context 中,每个元素左外边与包含块的左边相接触(对于从右到左的格式化,右外边接触右边), 即便存在浮动也是如此(尽管一个元素的内容区域会因为浮动而压缩),除非这个元素也建立了一个新的 Block Formatting Context 。code

从上面的定义咱们能够看到Document显示HTML元素的方式和BFC的定义很像,其实咱们能够认为Document就是最大的一个拥有BFC的元素了。orm

2. BFC究竟是什么?blog

当涉及到可视化布局的时候,Block Formatting Context提供了一个环境,HTML元素在这个环境中按照必定规则进行布局。一个环境中的元素不会影响到其它环境中的布局。好比浮动元素会造成BFC,浮动元素内部子元素的主要受该浮动元素影响,两个浮动元素之间是互不影响的。这里有点相似一个BFC就是一个独立的行政单位的意思。一个大的行政单位能够包含若干个小的行政单位。图片

3. 怎样才能造成BFCit

  • float的值不为none。
  • overflow的值不为visible。
  • display的值为table-cell, table-caption, inline-block中的任何一个。
  • position的值不为relative和static。

4. BFC的做用io

1. 清除内部浮动

咱们在布局时常常会遇到这个问题:对子元素设置浮动后,父元素会发生高度塌陷,也就是父元素的高度变为0。解决这个问题,只须要把把父元素变成一个BFC就好了。经常使用的办法是给父元素设置overflow:hidden。

2. 垂直margin合并

在CSS当中,相邻的两个盒子的外边距能够结合成一个单独的外边距。这种合并外边距的方式被称为折叠,而且于是所结合成的外边距称为折叠外边距。
折叠的结果:

  • 两个相邻的外边距都是正数时,折叠结果是它们二者之间较大的值。
  • 两个相邻的外边距都是负数时,折叠结果是二者绝对值的较大值。
  • 两个外边距一正一负时,折叠结果是二者的相加的和。
    这个一样能够利用BFC解决。关于原理在前文已经讲过了。

3. 建立自适应两栏布局

在不少网站中,咱们常看到这样的一种结构,左图片+右文字的两栏结构。

<div style="overflow:hidden;border: solid 1px;">
        <div style="background: cadetblue;float:left;width:200px;height:200px;margin: 10px;"></div>
        <div style="background: wheat;overflow:hidden;margin: 10px;padding: 10px;">
            &nbsp;&nbsp;&nbsp;&nbsp;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.
            <br/>
            &nbsp;&nbsp;&nbsp;&nbsp;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).
        </div> 
    </div> 

效果如图:

相关文章
相关标签/搜索