Search code examples
htmlcssz-indexoverlapping

Overlapping does not work when i set parent's z-index


When i set the parent's z index property, overlapping does not work. Here is the html and css:

.black_gradient{
  width:100%;
  height:100%;
  background: linear-gradient(0deg,rgb(75, 75, 75) 20%, rgba(75,75,75,0.8) 70%, rgba(75,75,75,0.3));
  position:relative;
  display:block;
  z-index:3;
}
.img_container{
  width: 100%;
  height: 100%;
  margin: 0 auto;
  position: relative;
  z-index:-2;
  display:inline-block; 
}
<div class="black_gradient">
   <div class="img_container">
      <img src="http://i48.tinypic.com/wrltuc.jpg" />
   </div>
</div>

And JSFiddler link. When i remove z-index from black_gradient, it works as expected. I read a few topic about overlapping and z index such as from mozilla dev page. But i couldn't figure it out why it does not work when i set z-index.


Solution

  • So Here is how it looks now JS Fiddle

    html, body{
      margin:0;
      padding:0;
      height:100%;
    }
    .img_container {
      width: 100%;
      height: 500px;
      margin: 0 auto;
      position: relative;
      display: inline-block;
    }
    .to_top.black_gradient {
      width: 100%;
      height: 100%;
      display:inline-block;
      background: linear-gradient(0deg, rgb(75, 75, 75) 20%, rgba(75, 75, 75, 0.8) 70%, rgba(75, 75, 75, 0.3));
      position: absolute;
      top:0;
      left:0;
    }
    <div class="img_container">
      <img style="" class="tall" src="http://i48.tinypic.com/wrltuc.jpg" />
      <div class="to_top black_gradient">
      </div>
    </div>

    T problem is caused by concept of stacking z-index, where the child elements have different stacking context independent from their parents, from MDN - The stacking context page:

    Each stacking context is completely independent from its siblings: only descendant elements are considered when stacking is processed.

    Also, from the Notes section:

    enter image description here

    • Root
      • DIV #2 - z-index is 2
      • DIV #3 - z-index is 4
        • DIV #5 - z-index is 1, stacked under an element with a z-index of 4, which results in a rendering order of 4.1
        • DIV #6 - z-index is 3, stacked under an element with a z-index of 4, which results in a rendering order of 4.3
        • DIV #4 - z-index is 6, stacked under an element with a z-index of 4, which results in a rendering order of 4.6
      • DIV #1 - z-index is 5

    So the issue previously was because that children always have higher z-index values from their parents because it is considered as another stacking context, just like DIV#5 and DIV#6 to their parent DIV#3 in the above example.