The Z-Index Property Tutorial
Learn All About Stacking CSS Elements with Z-Index

Passionate Software Engineer with three years of experience, dedicated to creating robust and scalable web applications. I have a strong foundation in JavaScript, React, Python, and Node.js, and enjoy working with modern tech stacks to build innovative solutions. I'm committed to writing clean and efficient code, following best practices, and staying updated with the latest industry trends.
Throughout my career, I've gained valuable experience in full-stack development, including frontend design, backend development, and database management. I love solving complex problems and implementing creative solutions that enhance user experiences. I believe in the power of collaboration and thrive in cross-functional teams where I can contribute my skills and learn from others.
Beyond coding, I am an avid learner and enjoy sharing my knowledge with the developer community. I regularly contribute to open-source projects, write technical blog posts, and engage in discussions on emerging technologies. I'm always seeking opportunities to expand my skill set and stay at the forefront of software engineering.
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!




