浮动和堆叠上下文

floats and Stacking Context

作为背景,下面是 W3C 的 CSS2.1 规范中的两个相关部分,chapter 9.

Within each stacking context, the following layers are painted in back-to-front order:

  1. the background and borders of the element forming the stacking context.
  2. the child stacking contexts with negative stack levels (most negative first).
  3. the in-flow, non-inline-level, non-positioned descendants.
  4. the non-positioned floats.
  5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
  6. the child stacking contexts with stack level 0 and the positioned descendants with stack level 0.
  7. the child stacking contexts with positive stack levels (least positive first).

...还有这个:

Within each stacking context, positioned elements with stack level 0 (in layer 6), non-positioned floats (layer 4), inline blocks (layer 5), and inline tables (layer 5), are painted as if those elements themselves generated new stacking contexts, except that their positioned descendants and any would-be child stacking contexts take part in the current stacking context.

问题

.float {
  background-color: red;
  margin-right: -25px;
  border: 5px solid green;
  float: left;
  color: gray;
  font-size: 5rem;
}
.old {
  background: aqua;
  font-size: 3rem;
}
.new {
  background: yellow;
  font-size: 3rem;
}
 <span class="old">tesssss</span>
 <div class="float">testTwo</div>
 <div class="new">foo</div>

对于第二个问题,如果我们检查 painting order,我们将得到这样的顺序:

  1. For all its in-flow, non-positioned, block-level descendants in tree order:
  2. If the element is a block, list-item, or other block equivalent: background color of element.

现在我们已经绘制了块元素的背景颜色.new

  1. All non-positioned floating descendants, in tree order. For each one of these, treat the element as if it created a new stacking context, but any positioned descendants and descendants which actually create a new stacking context are considered part of the parent stacking context, not this new one.

所以现在我们已经绘制了所有元素 .float(背景和内容),因为它创建了自己的堆叠上下文。所以我们应该根据绘制顺序规则绘制其中的所有内容,然后我们移动到下一个元素。

  1. Otherwise: first for the element, then for all its in-flow, non-positioned, block-level descendants in tree order:
    1. ...

在这一步我们将绘制 .new 元素和内联元素 .old

的内容

所以诀窍是 .new 元素分两个不同的步骤绘制,首先是背景,然后是内容。在这些步骤之间,我们绘制了浮动元素。