代码之家  ›  专栏  ›  技术社区  ›  icekomo

为嵌套在固定容器内的绝对位置设置Z索引

  •  0
  • icekomo  · 技术社区  · 7 年前

    我有一个标题标记,将固定属性设置为。在那个标题标签里,我有一个导航标签,我设置为绝对位置。我现在遇到的问题是,我似乎无法将标题标签拉到导航标签前面。即使将header标签设置为1000的z-index,将nav标签设置为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

    2 回复  |  直到 7 年前
        1
  •  2
  •   brouxhaha    7 年前

    position: fixed 子元素不能位于其父元素之后。技巧是在父元素上使用伪元素,它将充当子元素的兄弟姐妹。

    根据您所描述的,文本将位于标题颜色的后面。

    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 相反。如果你不需要 位置:固定 ,可以将父级上的任何其他位置与负值组合使用。 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;
    }
    <标题>
    <h1>您好</h1>
    
    <导航>
    <ul>
    <li><a href=“”>主页</a></li>
    <li><a href=“”>关于</a></li>
    <li><a href=“”>联系</a></li>
    </ul>
    </nav>
    </header>
        2
  •  0
  •   soalrib    7 年前

    我不知道我是否正确理解你想要的,但请检查一下

    Code Pen

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

    希望有帮助!