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;
}
The property takes a number, the higher the number, the closer the element is relative to the user.
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!).
Related Posts:
A little about me..
Hey, Iâm Tim! đ
Iâm a freelance business owner, web developer & author. I teach both new and experienced freelancers how to build a sustainable and successful freelancing business. Check out my Complete Guide to Freelancing if you'd like to find out more.
While you're here, you can browse through my blogs where I post freelancing tips, code tutorials, design inspiration, useful tools & resources, and much more! You can also join the newsletter, or find me on X.
Thanks for reading! đ