The Z-Index Property Tutorial
Learn All About Stacking CSS Elements with Z-Index
Table of contents
In CSS, each box has a position in three dimensions. In addition to the x-axis (horizontal) and y-axis (vertical) positions, boxes also have a βz-axisβ where they stack on top of each other.
The z-index
property defines the stacking order of the elements on the z-axis. It only works on elements that have a position defined (anything apart from the default position:static;
).
So when you have multiple overlapping elements on a page, z-index
lets you decide which one is visible (or nearer to the user), as well as the order of any element(s) that sit behind it.
For example:
.element1 {
/* other styles ... */
position: absolute;
z-index: 1;
}
.element2 {
/* other styles ... */
position: absolute;
z-index: 2;
}
And rather intuitively, if we swap our order values like so:
.element1 {
/* other styles ... */
position: absolute;
z-index: 2;
}
.element2 {
/* other styles ... */
position: absolute;
z-index: 1;
}
The stacking order will change: Negative numbers can also be used.
And when no z-index
value is set, elements stack in the order that they appear in our HTML.
A good rule of thumb is to allow for number gaps when working with z-index
. So using β10β then β20β for example. This way there is plenty of room to place an element within your stacking order, without having to re-number every element!
It should also be noted that nested elements behave differently. For example, a child element of element A will never be higher than element B, if B has a lower z-index
value (and therefore a higher stacking order!).
Conclusion
If you liked this blog post, follow me on Twitter where I post daily about Tech related things!