• 前端知识总结--BFC


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

    1. BFC的定义

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

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

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

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

    2. BFC到底是什么?

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

    3. 怎样才能形成BFC

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

    4. BFC的作用

    1. 清除内部浮动

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

    2. 垂直margin合并

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

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

    3. 创建自适应两栏布局

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

    <div style="overflow:hidden;border: solid 1px;">
            <div style="background: cadetblue;float:left;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> 

    效果如图:

  • 相关阅读:
    js中有哪些是循环遍历的方法?
    堆内存和栈内存
    Html5和Css3
    PyCharm IDE 的使用
    python基础语法
    数据挖掘书籍简介
    寄存器-2
    汇编基础
    Std::bind()
    手游页游和端游的服务端框架
  • 原文地址:https://www.cnblogs.com/fanlu/p/10796835.html
Copyright © 2020-2023  润新知