为什么负 z-index 在 Firefox 中隐藏了元素,但在 Chrome/Safari 中却没有

Why negative z-index hides element in Firefox but not in Chrome/Safari

<div class="parent">
   <div class="child">DIV which will be hidden in Firefox</div>
</div>

CSS:

.parent {
    width: 100%;
    position: fixed;
    bottom: 0px;
    height: 28px;
    border-top: 1px solid grey;
    background: #fff;
}

.child {
    position: absolute;
    width: 68%;
    background: greenyellow;
    left: 200px;
    z-index: -1;
}

在上面的代码中,子元素的 z-index-1。此元素在 Chrome/Safari 中可见,但在 Firefox 中不可见。为什么?哪一个行为正确?

Fiddle link

这叫做stacking context。如您所见,如果元素具有 position: fixed,则它会获得堆栈索引。一旦一个元素有一个堆栈索引,它们 children 的负数 z-index 而不是 隐藏它们。 所以我会说 Firefox 呈现错误,但老实说,我对此并不完全确定。

Here is an article 关于 Chrome,即:

In Chrome 22 the layout behavior of position:fixed elements is slightly different than previous versions. All position:fixed elements now form new stacking contexts.

还有:

The original version of this article suggested that the CSS z-index specification had already been changed to reflect the new behavior of position: fixed elements. This is inaccurate; it has been discussed on the www-style list but as of yet no change has been taken into the spec.

所以,实际上 Firefox 目前看起来是正确的,但规格可能很快就会改变。

当你给每个 DIV 背景颜色和 child z-index = -1 然后 child 设置在 parent 白色背景后面。

check running example [JSFiddle][1]

查看 specification in CSS 2.1 表明它实际上应该是可见的:

Each box belongs to one stacking context.

z-index 设置为整数时...

[...] The box also establishes a new stacking context.

The root element forms the root stacking context.

换句话说,您的 .child 因此将直接位于根堆栈上下文中,因为 .parent 没有定义明确的 z-index

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. [...]

因此,唯一可能隐藏具有负索引的元素将处于同一级别或 DOM 树的更下方。

但是如果您在 .parent 上设置 z-index: 0,它将出现,因此根堆栈上下文在 Firefox 中似乎表现不正确。