Search code examples
htmlcssz-index

z-index not working (not stacked), no background-color set


Problem

Having two divs and on scroll, we want one to disappear under the next one. We set the positions fixed for the first, relative for the second, correct z-indexes, but on scroll, they just overlap.

#first {
  height: 300px;
  position: fixed;
  top: 30px;
  z-index: 0;
}

#second {
  position: relative;
  height: 800px;
  margin-top: 200px;
  z-index: 1;
}

Expected behaviour

On scroll, the first div should disappear into the second one as per z-index stacking rules.

JSFiddle

https://jsfiddle.net/8mf4opsx/


Solution

  • Solution

    Because the second div does not have a default background color set, the background is transparent and the second div can be seen.

    The solution is to add a white background to the second div.

    #first {
      height: 300px;
      position: fixed;
      top: 30px;
      z-index: 0;
    }
    
    #second {
      position: relative;
      height: 800px;
      margin-top: 200px;
      z-index: 1;
      background-color: white;
    }
    

    JSFiddle

    https://jsfiddle.net/8mf4opsx/3/