CSS:z-index在position:relative容器内不起作用

3

我想要将.wall-paneldiv放在我的img后面(让图像可见),但保留fiddle中的所有其他定位。如果没有position: relative容器,这个方法是可行的,但一旦放到容器内部,z-index属性似乎就不起作用了。

我做错了什么?

.container {
  position: relative;
  top: calc(100vh * 0.4);
  left: 0;
  width: 100%;
}

.image {
  z-index: 1;
}

.wall-panel {
  width: 100%;
  background-color: red;
  height: 200px;
  position: absolute;
  top: 0;
  z-index: 0;
}
<div class='container'>
  <img class='image' src='http://lorempixel.com/400/400/'>
  <div class='wall-panel' />
</div>
<div>
Some other text that positions under the container.
</div>


3
顺便说一下,z-index对图像没有影响,因为它的位置是静态的。 - Fabrizio Calderan
4个回答

3

z-index应该为-1,这样就能正常工作:

.container {
  position: relative;
  top: calc(100vh * 0.4);
  left: 0;
  width: 100%;
}

.image {
  z-index: 1;
}

.wall-panel {
  width: 100%;
  background-color: red;
  height: 200px;
  position: absolute;
  top: 0;
  z-index: -1;
}
<div class='container'>
  <img class='image' src='http://lorempixel.com/400/400/'>
  <div class='wall-panel'>
</div>
<div>
Some other text that positions under the container.
</div>
</div>


1
由于 OP 已经接受了这个更好的方案,最好从图像中删除 z-index,以使代码连贯。实际上有点错误,因为 z-index 在那里没有意义。 - Temani Afif

1
使图片定位的原因是:

z-index CSS 属性指定了一个 定位 元素及其后代元素的 z 轴顺序。

https://developer.mozilla.org/en-US/docs/Web/CSS/z-index

并且

定位元素是指其计算后的 position 值为 relativeabsolutefixedsticky 的元素。换句话说,它除了 static 以外的任何值。

https://developer.mozilla.org/en-US/docs/Web/CSS/position

.container {
  position: relative;
  top: calc(100vh * 0.4);
  left: 0;
  width: 100%;
}

.image {
  z-index: 1;
  position: relative;
}

.wall-panel {
  width: 100%;
  background-color: red;
  height: 200px;
  position: absolute;
  top: 0;
  z-index: 0;
}
<div class='container'>
  <img class='image' src='http://lorempixel.com/400/400/'>
  <div class='wall-panel'></div>
</div>
<div>
  Some other text that positions under the container.
</div>


1

只需将 position: relative 应用于图片即可。它会起作用。


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接