Adamwu1992 / adamwu1992.github.io

My Blog
2 stars 0 forks source link

Block Formatting Contexts: 块级格式化上下文 #15

Open Adamwu1992 opened 5 years ago

Adamwu1992 commented 5 years ago

特征

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.

以上是来自W3C的定义,总结一下就是以下特征:

表现

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).

应用

  <div class="container bfc-container">
    <!-- 子元素上下边距各为10px -->
    <div class="child margin-10"></div>

    <!-- 第二个子元素和第一个子元素的margin重叠,距离只有10px -->
    <div class="child margin-10"></div>

    <!-- 第三个子元素属于一个新的BFC 和第二个子元素的距离是20px -->
    <div class="bfc-container">
      <div class="child margin-10"></div>
    </div>
  </div>
  <!-- 容器构成了一个BFC 浮动子元素也会参与高度计算 此时容器高度100px -->
  <div class="container bfc-container">
    <!-- 第一个子元素左浮动 宽高都是50px -->
    <div class="float-left width-50 height-50"></div>

    <!-- 第二个子元素右浮动 宽高都是100px -->
    <div class="float-right width-100 height-100"></div>
  </div>
  <div class="contianer bfc-container">
    <!-- 左边元素固定宽度 左浮动 -->
    <div class="float-left"></div>

    <!-- 右边元素宽度自适应 外边框紧贴着左边元素 -->
    <div class="right bfc-container"></div>
  </div>

参考