DEV Community

Cover image for Z-index in CSS explained

Z-index in CSS explained

urielbitton profile image Uriel Bitton ・2 min read

Z-index is a complex css property for beginners and gets confusing when used on many elements. Let's demonstrate how it works and explain the reasons why sometimes you can't get it to work properly.

The Z-index property is based on priorities and works like a stack of books on a desk. If we have many books on a desk and none of them are stacked on another then we can see all the books from a bird's eye view. But what happens if we place a book on top of another? This newly added book will hide the one underneath it, obviously. In real life we can't do anything to fix that except place them in bookcases, but in web design with CSS we can define which book in a stack we want to be visible.

The values of z-index range from -infinity to infinity. The higher the number the higher priority it has to be displayed over another element with lower priority.

For example: a div with z-index: 10 will be shown above a div with z-index: 5. That much, we all know. But here are 2 examples where it gets complicated.

Say we have div1 with z-index of 100 and div2 with z-index 50. Each div has a p tag inside it, the div1 p has a z-index of 200 and the div2 p has a z-index of 100. Now say we place these two divs, div1 and div2 at the same place on a web page, which p tag will be displayed on top? Its not the div p with the higher z-index! Why? Because div1 has a higher z-index than the z-index of div2. And priorities always go back to the parent element.

The other complication is when we don't specify a position to an element, the z-index will simply not work! Z-index needs a position, any position value, for z-index to work.

Whenever your z-index is not displaying properly, 99% of the time its either because you have not specified a posiiton or that another parent element has a higher z-index than the element you are trying to use z-index on.

I hope this clears things up on this elusive CSS property!

Discussion (6)

20nick06 profile image

By virtue all elements have a position of static so its safe to say z-index work for every other position except static.

urielbitton profile image
Uriel Bitton Author

Yes exactly. I didn't want to get into positions. I wanted to write about that in another post

shadowscientist profile image
Shadow Scientist

Nice explanation. It solved most of my confusions. 🥰

urielbitton profile image
Uriel Bitton Author

Awesome! Glad to hear!

robertotonino profile image
Roberto Tonino • Edited

I always forget the fact that the element must have a position lol, but maybe the DevTools could send us a better feedback!

ziizium profile image
Forem Open with the Forem app