Search code examples
htmlcsspositionabsolute

absolute positioned div appearing above everything else


I wanted a partial purple background that is positioned absolutely behind everything else. When I tried to make this, the div appeared on top of all of my other elements. Is there a way I can make that div appear behind everything instead? I tried using z-index to no avail and looked up some other posts, nothing seemed to work.

h1 {
  text-align: center;
}

#topColor {
  width: 100%;
  height: 400px;
  background-color: #9546c1;
  position: absolute;
  top: 0px;
  right: 0;
  z-index=-1;
}
<body>
  <div id="headerWrapper">
    <h1><img class="centeredImage" src="http://via.placeholder.com/150x150" alt="Logo"></h1>
  </div>
  <div id="navWrapper"> </div>
  <div id="topColor"> </div>
  <br>
  <div id="navigation"></div>
</body>


Solution

  • This is simply an error in css syntax, z-index = -1; should be z-index: -1;

    h1 {
      text-align: center;
    }
    
    #topColor {
      width: 100%;
      height: 400px;
      background-color: #9546c1;
      position: absolute;
      top: 0px;
      right: 0;
      z-index:-1;
    }
    <body>
      <div id="headerWrapper">
        <h1><img class="centeredImage" src="http://via.placeholder.com/150x150" alt="Logo"></h1>
      </div>
      <div id="navWrapper"> </div>
      <div id="topColor"> </div>
      <br>
      <div id="navigation"></div>
    </body>

    Although, you can also use background-color instead. Not really sure why you need to use position:absolute if it is only for background color. Just add height: 100%; to the body and html, and also for #topColor

    body,
    html {
      height: 100%;
    }
    
    h1 {
      text-align: center;
    }
    
    #topColor {
      background-color: #9546c1;
      height: 100%;
    }
    <body>
      <div id="topColor">
        <div id="headerWrapper">
          <h1><img class="centeredImage" src="http://via.placeholder.com/150x150" alt="Logo"></h1>
        </div>
        <div id="navWrapper"> </div>
        <br>
        <div id="navigation"></div>
      </div>
    </body>