CSS:z索引无法在位置内部工作:相对容器



我想将.wall-panel div定位在我的img后面(以便可见图像(,但保留在小提琴中的所有其他位置。这可以在没有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>

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>

只需应用位置:也相对于图像。它将起作用。

使图像放置在:

z-index css属性指定定位的z订单 元素及其后代

https://developer.mozilla.org/en-us/docs/web/css/z-index

位置元素是一个元素,其计算位置值为 相对绝对 filex sticky 。(换句话说,是 除静态外,任何东西。(

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>

如果要使用z-index,则必须在块中添加position: relative

请参阅jsfiddle https://jsfiddle.net/andrewsilent/ber9weqw/

最新更新