为什么 z-index 为 0 的元素显示在 z-index 为 1 的元素上方

Why element with z-index 0 is shown above element with z-index 1

我有以下代码(示例):

<div style="position: fixed">
  <div id="AAA" style="position: absolute; background-color: green; z-index: 1">AAA</div>
</div>
<div style="position: relative">
  <div id="BBB" style="position: absolute; background-color: red; z-index: 0">BBB</div>
</div>

对我来说,AAA div 应该显示在 BBB div 之上,因为:

但在结果HTML中,BBB 显示在 AAA 之上。为什么?是否有描述此行为的文档?

因为父级上的 positionz-index 开始了新的堆叠顺序。特别是 position: fixed 在第一个元素上。 https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context

A stacking context is formed, anywhere in the document, by any element in the following scenarios:

...

Element with a position value "fixed" or "sticky" (sticky for all mobile browsers, but not older desktop).

所以第一个 div 的子 z-index 是相对于父文档的,而不是文档的其余部分。

在此示例中,您想将 z-index 应用于父级。

<div style="position: fixed; z-index: 1;">
  <div id="AAA" style="position: absolute; background-color: green; z-index: 1">AAA</div>
</div>
<div style="position: relative;">
  <div id="BBB" style="position: absolute; background-color: red; z-index: 0">BBB</div>
</div>