使用 z-index 使 div 高于另一个 div

Using z-index to get div above another div

我希望 div1 高于 div2。我尝试使用 z-index 但它不起作用。

我试过这个代码:

div {
  width: 100px;
  height: 100px;
}

.div1 {
  background: red;
  z-index: 1;
}
.div2 {
  background: blue;
  margin-top: -15vh;
  z-index: 2
}
<div class="div1"></div>
<div class="div2"></div>

您可以将 position: relative 添加到两个 div 并创建 stacking context

div {
  width:100px;
  height: 100px;
}

.div1 {
  background: red;
  z-index: 2;
  position: relative;
}

.div2 {
  background: blue;
  margin-top: -15vh;
  z-index: 1;
  position: relative;
}
<div class="div1"></div>
<div class="div2"></div>

或者你可以使用 transform-style: preserve-3d; 所以现在 .div1 应该位于 3D-space 而不是在平面上展平。

div {
  width:100px;
  height: 100px;
}

.div1 {
  background: red;
  z-index: 2;
  transform-style: preserve-3d;
}

.div2 {
  background: blue;
  margin-top: -15vh;
  z-index: 1;
}
<div class="div1"></div>
<div class="div2"></div>

你也可以使用一些随机的transform like translate or rotate

div {
  width:100px;
  height: 100px;
}

.div1 {
  background: red;
  z-index: 2;
  transform: translate(1px);
}

.div2 {
  background: blue;
  transform: translate(1px, -15vh);
  z-index: 1;
}
<div class="div1"></div>
<div class="div2"></div>

Filters also work but they have bad Support

div {
  width:100px;
  height: 100px;
}

.div1 {
  background: red;
  filter: brightness(0.4);
  z-index: 2;
}

.div2 {
  background: blue;
  margin-top: -15vh;
  filter: brightness(0.4);
  z-index: 1;
}
<div class="div1"></div>
<div class="div2"></div>

在许多情况下,必须定位元素才能 z-index 工作。

确实,将 position: relative 应用于问题中的 div 将解决 z-index 问题。

实际上,position: fixedposition: absoluteposition: sticky 也会启用 z-index,但这些值也会更改布局。使用 position: relative 布局不会受到干扰。

本质上,只要元素不是 position: static(默认值),它就被视为已定位,并且 z-index 将起作用。


此处和相关问题中的一些答案断言 z-index 对定位元素有效。从 CSS3 开始,这不再是事实。

即使 positionstaticflex items or grid items 的元素也可以使用 z-index

来自规格:

4.3. Flex Item Z-Ordering

Flex items paint exactly the same as inline blocks, except that order-modified document order is used in place of raw document order, and z-index values other than auto create a stacking context even if position is static.

5.4. Z-axis Ordering: the z-index property

The painting order of grid items is exactly the same as inline blocks, except that order-modified document order is used in place of raw document order, and z-index values other than auto create a stacking context even if position is static.

下面是 z-index 处理非定位弹性项目的演示:https://jsfiddle.net/m0wddwxs/

z-index 仅适用于具有 position 而不是 static 的元素,例如:relativeabsolutefixed.

div {
  width:100px;
  height: 100px;
  position:relative;
}
.div1 {
  background: red;
  z-index: 2;
}
.div2 {
  background: blue;
  margin-top: -15vh;
  z-index: 1
}
<div class="div1"></div>
<div class="div2"></div>

div 的默认 属性 是 position:static,在两个 div 中添加 position:relative 然后只有 z-index 有效。