绝对元素z-index中的固定元素不起作用

时间:2019-01-31 11:39:33

标签: html css css3 css-position

我得到了两个absolute和相同的z-index元素。 其中一个有一个fixed-position的孩子,该孩子的z-index比父母的孩子高。

为什么子级只与父级重叠,而另一个绝对值较低的z-index却不重叠。 如何实现孩子与两个较低的z-index元素重叠?

.lower-element {
  background: green;
  width: 3em;
  height: 3em;
  position: absolute;
  z-index: 10;
}

.higher-element {
  background: blue;
  width: 100vw;
  height: 100vh;
  position: fixed;
  opacity: .5;
  z-index: 20;
}

.lower-element-1 {
  top: 5em;
}
<div class="lower-element">
  <div class="higher-element">
  </div>
</div>

<div class="lower-element lower-element-1">
</div>

3 个答案:

答案 0 :(得分:2)

position: fixedposition: absolute仅可用于topbottomleftright值。

.lower-element {
  background: green;
  width: 3em;
  height: 3em;
  position: absolute;
  z-index: 10;
}

.higher-element {
  background: blue;
  width: 100vw;
  height: 100vh;
  position: fixed;
  opacity: .5;
  z-index: 20;
  top:5em; /* I added */
}

.lower-element-1 {
  top: 5em;
}
<div class="lower-element">
  <div class="higher-element">
  </div>
</div>

<div class="lower-element lower-element-1">
</div>

答案 1 :(得分:1)

删除所有z-index并仅添加到.higher-elementz-index: -1;

.lower-element {
  background: green;
  width: 3em;
  height: 3em;
  position: absolute;
}

.higher-element {
  background: blue;
  width: 100vw;
  height: 100vh;
  position: fixed;
  opacity: .5;
  z-index: -1;
}

.lower-element-1 {
  top: 5em;
}
<div class="lower-element">
  <div class="higher-element">
  </div>
</div>

<div class="lower-element lower-element-1">
</div>

答案 2 :(得分:1)

通过使.higher-element.lower-element成为兄弟姐妹,然后将.higher-elementz-index: -1设置

.lower-element {
  background: green;
  width: 3em;
  height: 3em;
  position: absolute;
  z-index: 10;
}

.higher-element {
  background: blue;
  width: 100vw;
  height: 100vh;
  position: fixed;
  opacity: .5;
  z-index: -1;
}

.lower-element-1 {
  top: 5em;
}
<div class="lower-element"> 
</div>
<div class="higher-element">
</div>
<div class="lower-element lower-element-1">
</div>