具有较高 z-index 值的元素不覆盖另一个

element with higher z-index value not overlaying another

我有这个代码

#mtitle {
  display: inline-block;
  margin: 0;
  background-color: #000000;
  z-index: 999;
}
#tsub {
  display: inline-block;
  margin-left: 0;
  left: 0;
  position: absolute;
  font-size: 85px;
  z-index: 0;
}
<header>
  <h1 id="mtitle">Tepid Beans</h1>
  <div id="tsub"><span>- Games</span>
  </div>
</header>

#tsub 出现在 #mtitle 之上,我不知道为什么。

z-index 仅适用于定位的元素。因此,如果您将 position: relative; 添加到 #mtitle,z 索引将起作用。

z-index 适用于定位元素,但对于 flex items or grid items 的 CSS3 元素,当元素为静态

时可以使用 z-index

来自MDN

The z-index property specifies the z-order of an element and its descendants. When elements overlap, z-order determines which one covers the other. An element with a larger z-index generally covers an element with a lower one.

For a positioned box, the z-index property specifies:

  • The stack level of the box in the current stacking context.

  • Whether the box establishes a local stacking context.

Applies to positioned elements

position:relative 设置为父级 header 并将 position:absolute 设置为 #mtitle 并更改 z-index

body {
  margin: 0
}
header {
  position: relative
}
#mtitle {
  display: inline-block;
  background-color: #000000;
  position: absolute;
  margin:0;
  z-index: 0;
  color: #fff
}
#tsub {
  display: inline-block;
  left: 0;
  position: absolute;
  font-size: 85px;
  z-index: -1;
  background: red
}
<header>
  <h1 id="mtitle">Tepid Beans</h1>
  <div id="tsub">- Games</div>
</header>

虽然此处发布的其他答案解决了问题,但它们并不完全正确。

下列说法是错误的:

  • z-index only works on positioned elements.
  • z-index only works on elements that are positioned.
  • z-index only works on elements which are not position:static ie the default position.

在许多情况下,必须定位元素才能使 z-index 起作用。但这并非适用于所有情况。

属于 flex items or grid items can create stacking contexts with z-index, even when position is static (see demo) 的元素。

就这个具体问题而言,#tsub 出现在 #mtitle 之上的原因是:

  1. div#tsub 在 HTML 中的 h1#mtitle 之后,AND
  2. 应用到 #mtitlez-index 属性 被忽略,因为 #mtitle 没有定位,也不是弹性或网格项目。

这里有两种可能的解决方案:

  1. #tsub 上的 z-index: 0 更改为 z-index: -1,或者
  2. position: relative 添加到 #mtitle

#mtitle {
  display: inline-block;
  margin: 0;
  background-color: aqua;  /* changed for illustration purposes */
  z-index: 999;
}
#tsub {
  display: inline-block;
  margin-left: 0;
  left: 0;
  position: absolute;
  font-size: 85px;
  z-index: -1;   /* adjustment here */
}
<header>
  <h1 id="mtitle">Tepid Beans</h1>
  <div id="tsub"><span>- Games</span>
  </div>
</header>

关于你问题的最后一部分,

tsub is appearing on top of #mtitle, and I do not know why.

带有 position: absolute 的元素从元素的常规流中“取出”,它们不会在其父元素中占用任何 space(需要位置设置而不是 static 为了使它起作用),它们只固定在它们上面(= 将与它们一起移动)。但这样它们就可以与其他元素重叠。

在几个绝对定位的元素中,z-index 将决定哪个在另一个之上..