Search code examples
htmlcssz-index

z-index not working properly?


I have the HTML:

<div class="arrow" id="link1">
    <img class="bellow" src="bottom.jpg" width="305" height="229" />
</div>

And the CSS:

.arrow {
  display: block;
  width: 305px;
  height: 229px;
  z-index: 10;
  position: relative;
  background-image: url(top.png);
}

#link1 {
  background-position: 0 458PX;
  z-index: 10;
  position: absolute;
}

#link1:hover {
  background-position: 0 229px;
  z-index: 10;
  position: absolute;
}

.bellow {
  z-index: 1;
  position: absolute;
}

But the background-image is not showing up on top of the bottom.jpg what is wrong with the z-index?


Solution

  • body (or any other positioned parent element) is the reference for both the child and and parent element

    source: z-index between Children and Parents

    This means the z-index on your parent also applies to the child element. Where the child element(image) will also take z-index: 10;. With the parent and child both have a z-index of 10, the child will actually be rendered over the parent.

    To fix this you should not even give a z-index to the parent, but only to the child(the image):

    .bellow {
        z-index: -1;
        position:absolute;
    }
    

    Where the image will have a lower value as the default value, thus will be underneath its parent.

    jsFiddle