Search code examples
htmlcssnavigationpositionz-index

How do I fix the z-index with an absolute nav bar and a relative image?


so, I'm trying to have an absolutely positioned navigation bar, stacked on top of an image, I would like it set so that the navigation changes to a solid color background on scroll, but the issue I'm running into is with the z-index. The navigation just refuses to stack over the image, which is positioned relative. The two items are also siblings in the html, so there shouldn't be an issue with the parent overshadowing the child element.

nav {
  text-align: right;
  width: 100%;
}

nav ul li {
  position: absolute;
  top: 0;
  z-index: 100;
}

nav li {
  display: inline;
  width: 100%;
}

li {
  list-style-type: none;
  width: 100%;
  padding: 5px;
}

#hero-image {
  width: 100vw;
  height: 100vh;
  margin: 0;
  padding: 0;
  z-index: -1;
  position: relative;
}
<nav id="top-nav">
  <ul class="nav-list">
    <li class="nav-item">Home</li>
    <li class="nav-item">Course Catalog</li>
    <li class="nav-item">Products &amp; Services</li>
    <li class="nav-item">About</li>
    <li class="nav-item">Contact</li>
  </ul>
</nav>

<img id="hero-image" src="https://res.cloudinary.com/spacecatind/image/upload/v1568288870/The%20Line%2C%20LLC/tower-sunset_qtqa0q.jpg"></img>


Solution

  • Add this to your nav css

      position: absolute;
      top: 0;
      z-index: 100;
    

    The reason it was not working was because, you were making the inner li items position:absolute

    Instead of doing this, make the parent nav position:absolute

    nav {
      text-align: right;
      width: 100%;
      position: absolute;
      top: 0;
      z-index: 100;
    }
    
    nav ul li {
      
    }
    
    nav li {
      display: inline;
      width: 100%;
    }
    
    li {
      list-style-type: none;
      width: 100%;
      padding: 5px;
    }
    
    #hero-image {
      width: 100vw;
      height: 100vh;
      margin: 0;
      padding: 0;
      z-index: -1;
      position: relative;
    }
    <nav id="top-nav">
      <ul class="nav-list">
        <li class="nav-item">Home</li>
        <li class="nav-item">Course Catalog</li>
        <li class="nav-item">Products &amp; Services</li>
        <li class="nav-item">About</li>
        <li class="nav-item">Contact</li>
      </ul>
    </nav>
    
    <img id="hero-image" src="https://res.cloudinary.com/spacecatind/image/upload/v1568288870/The%20Line%2C%20LLC/tower-sunset_qtqa0q.jpg"></img>