The Z-Index Property Tutorial

The Z-Index Property Tutorial

Learn All About Stacking CSS Elements with Z-Index

Β·

2 min read

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; 
}

Z-Index-1 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: Z-Index-2 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!

🌎 Let's Connect

Did you find this article valuable?

Support Richard Rembert by becoming a sponsor. Any amount is appreciated!

Β