为什么浏览器不尊重具有 "position: fixed" 父级的元素的 z-index?

Why doesn't the browser respect the z-index of an element with a "position: fixed" parent?

所以我有这个 fiddle:

https://jsfiddle.net/ionescho/t0qo6z5u/。 html :

<div id="overlay">
</div>

<div id="top_menu">
    <span>
        fasdfsfafasdfas
    </span>
</div>

和css:

#overlay{
    position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1100;
  background-color: #000;
  opacity: 0.8;
}
#top_menu{
    position:fixed;
    top:0;
    left:0;
    right:0;
    height:200px;
    background-color:red;
    padding-top:40px;
    padding-left:40px;
}
#top_menu > span{
    font-weight:bold;
    color:white;
    font-size:30px;
    z-index:1101;
    position:relative;
}

如您所见,白色文字仍在半透明覆盖层后面。如果我将 span 的父级 (#top_menu) 从 "position:fixed" 修改为 "position:relative",我会得到我正在寻找的 z-index 行为。

但是,我不能失去那个"position:fixed" 属性。 有谁知道为什么会这样,我该如何解决?

谢谢。

我不确定你想要达到什么目的。 跨度 - 作为 #top_menu 的子项从其父项继承 z-index。您想让菜单位于叠加层之上吗?在这种情况下,#top_menu 需要 z-index 属性。 如果您只希望跨度位于顶部,则必须将其移出父容器并固定文本本身的位置。

您目前期望的行为是标准行为,并且适用于 Firefox。

然而,根据 this answer

this behavior is slated to be changed for elements with position: fixed such that they will always establish stacking contexts regardless of their z-index value. Some browsers have begun to adopt this behavior, however the change has not been reflected in either CSS2.1 or the new CSS Positioned Layout Module yet, so it may not be wise to rely on this behavior for now.

然后,如果 #top_menu 建立了一个堆叠上下文,#top_menu > spanz-index 将在该堆叠上下文中设置其 z 位置。但是,#top_menu 低于 #overlay

要解决此问题,您可以将 z-index 设置为 #top_menu(从而在所有浏览器上生成堆栈上下文),其值高于 #overlay 的值。但是,#top_menu 的背景将在 #overlay.

的前面
#top_menu {
  z-index: 1101;
}

#overlay {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1100;
  background-color: #000;
  opacity: 0.8;
}
#top_menu {
  position: fixed;
  z-index: 1101;
  top: 0;
  left: 0;
  right: 0;
  height: 200px;
  background-color: red;
  padding-top: 40px;
  padding-left: 40px;
}
#top_menu > span {
  font-weight: bold;
  color: white;
  font-size: 30px;
  z-index: 1101;
  position: relative;
}
<div id="overlay"></div>
<div id="top_menu">
  <span>fasdfsfafasdfas</span>
</div>