浮动元素是否像定位元素一样创建单独的堆叠上下文?

Do floated elements create a separate stacking context like positioned ones do?

最近我点亮了 an interesting article about the CSS z-index property. I found it because I was seeking for an answer about why overflowed text from a preceding div was displayed above the background of a following div but not above the background of a span in the following div, like here (jsfiddle):

#overflowed {
  background-color: green;
  width: 300px;
  height: 100px;
}
#non-floated {
  background-color: pink;
  width: 300px;
}
#non-floated span {
  background-color: yellow;
}

对此的解释是浏览器以特定顺序绘制元素,这是基于所谓的堆叠顺序:

因此对于布局中的根元素和每个定位元素,浏览器会创建这样的堆叠顺序,然后绘制所有这些顺序,抱歉双关语,各自的顺序。

所以这就是为什么 内联元素和文本(那些创建 内联框)被绘制在块级元素之上的原因,即使这些块元素稍后出现在文档中,就像我上面的 jsfiddle 中那样。


所以问题本身.

我仍然找不到答案,为什么这些 内联框 ,如果它们被创建,对于浮动元素内的内联元素和文本不与外部的其他内联框一起绘制浮动元素根据上面的堆叠顺序方案,像这里 (jsfiddle):

#overflowed {
  background-color: green;
  width: 300px;
  height: 100px;
}
#floated {
  background-color: pink;
  width: 300px;
  float: left;
}
#floated span {
  background-color: yellow;
}

在这里你可以清楚地看到,文档中第一个 div 的文本没有浮动,绘制在 span 的黄色背景之上(之后),而 span 是一个内联元素,并且根据上面堆叠顺序的图像应该是在浮动容器(它的背景和边框)之后绘制的。

那么有人对此有可靠的解释吗?我想浮动元素会创建一些类似它们自己的堆叠顺序的东西,就像定位元素一样,但我还没有在网络上找到任何提及。

CSS2.1指定元素的绘制顺序如下:

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

浮动不会自行建立堆叠上下文。只有当它们位于 具有非自动的 z-index(不包括 any of the numerous other ways an element may do so)时,它们才会这样做。否则,它们将与其他元素(包括内联元素)参与相同的堆栈上下文,但需要注意以下内容(来自上面的 link):

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.

因为你的 fiddle 中的所有元素都参与了相同的堆栈上下文,并且你的浮动元素没有定位(#4),溢出的内联内容 div (#5)在浮动元素其后代元素上方绘制,即使浮动元素在源代码顺序中出现得较晚。

溢出的 div (#1) 的 background 绘制在浮动背景下方,但是,因为浮动背景被认为是根据上面的第二个引用浮动自己。你可以通过giving the float a negative margin:

看到这个
#floated {
  background-color: pink;
  width: 300px;
  float: left;
  margin-top: -50px;
}