z-index 不影响元素显示的顺序

z-index not affecting the order in which elements are displayed

我无法理解 z-index 的概念。由于某种原因,灰色框出现在最底部。然后是黑盒子,在它们上面是红盒子。恰恰相反。 感谢您的帮助!

HTML:

<div id="gray-box">
  <div id="black-box"><div>
  <div id="red-box"></div>
</div>

CSS:

#gray-box {
  position: relative;
  z-index: 2;
  background-color: gray;
  width: 100%;
  height: 4rem;
}

#black-box {
  position: relative;
  z-index: 1;
  background-color: black;
  width: 20rem;
  height: 4rem;
}

#red-box {
  position: relative;
  z-index: 0;
  background-color: red;
  width: 20rem;
  height: 4rem;
}

我认为问题在于您有一个 div 未关闭。 此处:<div id="block-box"><div> 结束 div 标记中缺少 /

如果这是您正在寻找的版本,这里有一个可用的版本。 https://codepen.io/norbertbiro/pen/pozxpQP

您在 'black-box' 元素上的结尾 <div> 不正确。确保以正斜杠 </div>

结束

首先,您缺少黑框关闭 div 的关闭斜线,这导致 DOM 关闭。

其次,灰色框是其他两个 div 的父级,因此它总是在它们下面,除非您将子级 div 完全移出流程,并给它们一个负的 z-index。例如,我给黑色和红色框一个 position:absolute,并将灰色框更改为默认值 position: static,因此红色和黑色框不再被视为灰色框的子项:

#gray-box {
  position: static;
  background-color: gray;
  width: 100%;
  height: 4rem;
}

#black-box {
  z-index: -1;
  background-color: black;
  width: 20rem;
  height: 4rem;
  position: absolute;
  top: 20px; left: 20px
}

#red-box {
  z-index: -2;
  background-color: red;
  width: 20rem;
  height: 4rem;
  position: absolute;
  top: 30px; left: 30px;
}
<div id="gray-box">
  <div id="black-box"></div>
  <div id="red-box"></div>
</div>

阅读此 post,我认为它会消除您的误解。它解释了父元素的 z-index 与子元素无关。我认为这就是您试图通过将父项的 z-index 设置为高于子项来实现的目标。

How to make child element higher z-index than parent?