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:
<div>
<img class="not-positioned" src="http://placekitten.com/g/200/300">
<img class="positioned" src ="http://placekitten.com/g/400/500">
</div>
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.
Note: z-index only works on positioned elements (position: absolute, position: relative, position: fixed, or position: sticky) and flex items (elements that are direct children of display:flex elements).
You set z-index on a static element By default, every element has a position of static. z-index only works on positioned elements (relative, absolute, fixed, sticky) so if you set a z-index on an element with a static position, it won't work.
The z-index property determines the stack level of an HTML element. The “stack level” refers to the element's position on the Z axis (as opposed to the X axis or Y axis). A higher value means the element will be closer to the top of the stacking order. This stacking order runs perpendicular to the display, or viewport.
z-index is used to specify a stacking order other than the default. To move an element closer to the top of the stack (i.e., visually closer to the user), a positive integer value is assigned to the z-index property of the element.
Elements are positioned in all three dimensions
left
and right
top
and bottom
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;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With