While reviewing code, I see that a lot of projects setting
z-index: 9999999 to have element they want to come out on top; however, they didn’t know that maybe setting
z-index: 10 could also make this work.
There will also be cases where you will see that eventually
z-index: 9999999 cannot save your day out of the missionary “making the element on top of everything”.
First of all, let take a look at the below image to see how
z-index stack up compare to browser viewport
By default, the stacked elements will have the following order of z-index. This order assumed that no z-index being applied for these elements.
Background and borders — of the element forming the stacking context. The lowest level in the stack.
Negative Z-Index — the stacking contexts of descendants elements with negative z-index.
Block Level Boxes — in-flow non-inline-level non-positioned descendants.
Floated Boxes — non-positioned floats
Inline Boxes — in-flow inline-level non-positioned descendants.
Z-index: 0 — positioned elements. These form new stacking contexts.
Positive Z-index — positioned elements. The highest level in the stack.
As you can see, we have the default
z-index order, so if we started with 1, 2 or 3, we all can clearly see that the need for a
99999 z-index value is not necessary.
Tell me WHY 9999999 z-index value didn’t work?
Ok, calm down. Z-index is doesn’t work as a flat surface that any element with higher
z-index value can come out on top.
z-index will be calculated based on its parent element also (if it has any)
Let’s take an example like below: I will have classes with
z-index value as following:
one : z-index 10
one-child: z-index 200
two: z-index 20
three: z-index: 30
These value will be calculated based on our structure on HTML below:
Turn out, it will be assigned following value:
one : 10
one-child : 10.200
two : 20
I setup the example on jsfiddle. You can take a look and modify value on your own and see how it works.
Another example that I found on Google, which is every good at demonstrating how z-index works for elements.
References: tutsplus.com | css-tricks.com | smashmagazine.com