7

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Blake Frederick
  • 1,510
  • 20
  • 31

2 Answers2

5

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;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mmgross
  • 3,064
  • 1
  • 23
  • 32
1

From Mozilla Developer Network - position:

The position CSS property chooses alternative rules for positioning elements, designed to be useful for scripted animation effects.

Thus, in order to change an elements position, you need to tell it not to be static and you do that by applying a position property.

Further reading:

https://developer.mozilla.org/en-US/docs/tag/Understanding_CSS_z-index

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Michael Doye
  • 8,063
  • 5
  • 40
  • 56