The z-index is a powerful yet confusing concept of CSS. Let's make it easy!
z-index is a CSS property that controls stacking order of elements along a z-axis. Let's first take a look at what the z-axis is, and then get you started with a few tips to help you solve situations that tend to trip up developers.
Imagine a hypothetical line starting from your eye to screen. That is z-axis. It works like this:
The biggest thing that confuses developers is that z-index only works on positioned elements. You must specify the
position rule (
fixed) if you want to arrange an element using z-index.
/* bad - z-index will not work without position */
/* good - z-index works when position is applied */
By default, all elements have a z-index of 0. When z-index rules are the same and two elements collide, an element written father down your HTML code will be stacked on top.
Take two sibling elements,
b is written after
<!-- #b will have stacking precedence if no z-index is specified -->
By default, if both of these elements are positioned in such a way that they overlap, but neither has a z-index,
b will be stacked on top of
Using the example with
b above, let's say
b is intentionally stacked on
a. And let's say
a has a child,
c, which we give a z-index of
100. The HTML might look like this:
And the corresponding CSS:
In this case, the child(ren) of
c) can never be stacked above
b. This is how it plays out on the screen:
Here is some test code you can play around with for better understanding.
Dive deep into CSS position with real examples.