具有固定父级的绝对定位元素上的 z-index

z-index on absolute positioned element with fixed parent

为什么 z-index 属性 不适用于位置绝对的元素,如果该元素的父元素位置固定? 我为这种情况做了简单的 example

HTML:

<div id='q1'>
  <div id='q2'></div>  
</div>

CSS:

#q1 {
  position: fixed;
  width: 100%;
  height: 50px;
  background-color: red;
  z-index: 0;
}

#q2 {
  position: absolute;
  top: 80%;
  border: 2px solid black;
  width: 100px;
  height: 30px;
  background-color: green;
  z-index: -1;
}

不能那样做,因为 z-index 是相对于同一堆栈的元素的,在您的情况下,您希望 child 的 z-index 低于该值parent。

顺便说一下,如果你不把#q2 变成#q1 的 child,它就会像魅力一样发挥作用。

希望对您有所帮助

与位置属性无关,因为q2嵌套在q1

里面