为固定容器内嵌套的绝对位置设置 Z-index

Setting Z-index for a absolute position nested inside of a fixed container

我有一个 header 标签,我设置了一个固定的 属性。在那个 header 标签内,我有一个我设置为绝对定位的导航标签。我遇到的问题是我似乎无法将 header 标签拉到导航标签前面。即使将 header 标签设置为 1000 的 z-index 并将导航标签设置为 500 的 z-index。我正在尝试做的事情可能吗?

<header> <-- fixed position
   <section> logo here </section>
   <nav data-nav="main-navigation">   <-- absolute position
      <ul>
         <li><a href="#" id="selected">HOME <div></div></a></li>
         <li><a href="#">ABOUT US</a></li>
         <li><a href="#">SERVICES</a></li>
         <li><a href="#">GALLERIES</a></li>
         <li><a href="#">BLOG</a></li>
         <li><a href="#">CONTACT US</a></li>
      </ul>
     </nav>
  </header>

这里有一支代码笔来展示我正在尝试做的事情

CSS position codepen

对于 position: fixed,child 元素不能位于其 parent 后面。诀窍是在 parent 上使用 pseudo-element,它将充当 child.

的同级

根据您的描述,文字将在 header 颜色后面。

header{
  position: fixed;
  width: 100%;
  height: 100px;
}

header::before {
  content: '';
  position: absolute;
  height: 100%;
  z-index: 100;
  width: 100%;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: red;
}

header nav{
  position: fixed;
  background-color: blue;
  width: 50%;
  height: 50vh;
  top:0;
}

header ul{
  list-style:none;
}

header a{
  color: #fff;
}
<header>
  <h1>HELLO</h1>
  
  <nav>
    <ul>
      <li><a href="#">Home</a></li>
      <li><a href="#">About</a></li>
      <li><a href="#">Contact</a></li>
    </ul>
  </nav>
</header>

如果您希望文本显示在红色上方,则需要在 nav 上使用 pseudo-element。如果不需要 position: fixed,可以在 parent 上使用任何其他定位,并在 child 上使用负值 z-index

header{
  position: absolute;
  width: 100%;
  background-color: red;
  height: 100px;
}

header nav{
  position: absolute;
  background-color: blue;
  width: 50%;
  height: 50vh;
  top:0;
  z-index: -1;
}

header ul{
  list-style:none;
}

header a{
  color: #fff;
}
<header>
  <h1>HELLO</h1>
  
  <nav>
    <ul>
      <li><a href="#">Home</a></li>
      <li><a href="#">About</a></li>
      <li><a href="#">Contact</a></li>
    </ul>
  </nav>
</header>

我不知道我是否理解正确你想要什么,但是检查这个

Code Pen

基本上我改变了position并改变了一些HTML。

希望对您有所帮助!