DEV Community

Cover image for Z-index in CSS explained
Uriel Bitton
Uriel Bitton

Posted on • Updated on

Z-index in CSS explained

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, naturally.

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 -2147483647 to 2147483647 (basicallt -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 of 10 will be shown above a div with z-index of 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, most of the time its either because you have not specified a position 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!

Top comments (5)

Collapse
 
20nick06 profile image
Nick

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

Collapse
 
urielbitton profile image
Uriel Bitton

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

Collapse
 
urielbitton profile image
Uriel Bitton

Awesome! Glad to hear!

Collapse
 
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!

Collapse
 
ziizium profile image
Habdul Hazeez