Why does z-index only work for positioned elements?

0

Issue

I know that z-index only works with positioned elements, but I am wondering why this is the case. Is there a good reason for this behaviour or is it just one of those semi-arbitrary specification decisions?

I came across this issue when working with code like this:

HTML

<div>
    <img class="not-positioned" src="http://placekitten.com/g/200/300">
    <img class="positioned" src ="http://placekitten.com/g/400/500">
</div>

CSS

img {
    border: 2px solid black;
}

.positioned {
    position: relative;
    left: -60px;
    z-index: 1;
}

.not-positioned {
    z-index: 99;
}

http://jsfiddle.net/666nzL6j/

You’ll notice that this works according to specification (the .not-positioned image is behind the .positioned image despite .not-positioned‘s higher z-index value), but I am having a hard time understanding the rationale for this behaviour.

Solution

Elements are positioned in all three dimensions

  • on the x-axis using left and right
  • on the y-axis using top and bottom
  • on the z-axis using z-index

Of course, z-index is not 100% similar to the others, as it only describes a stacking instead of a "real" position, but that’s all you can do on the z-axis, since you don’t have fixed boundaries on that axis.

So, you need to give an element a position value other than static if you want to set its z-index. If your problem is as simple as in your example, you can also give the other element a negative z-index:

.positioned {
    position: relative;
    left: -60px;
    z-index: -1;
}

Answered By – mmgross

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More