ref: https://philipwalton.com/articles/what-no-one-told-you-about-z-index/
First of all, z-index only works on positioned elements. If you try to set a z-index on an element with no position specified, it will do nothing. Secondly, z-index values can create stacking contexts, and now suddenly what seemed simple just got a lot more complicated.
Stacking Contexts
Groups of elements with a common parent that move forward or backward together in the stacking order make up what is known as a stacking context.
New stacking contexts can be formed on an element in one of three ways:
- When an element is the root element of a document (the
<html>
element) - When an element has a position value other than
static
and a z-index value other thanauto
- When an element has an opacity value less than
1
The first and second ways to form stacking context make a lot of sense and are generally understood by Web developers (even if they don’t know what they’re called).
Stacking Order Within the Same Stacking Context
Here are the basic rules to determine stacking order within a single stacking context (from back to front):
- The stacking context’s root element
- Positioned elements (and their children) with negative z-index values (higher values are stacked in front of lower values; elements with the same value are stacked according to appearance in the HTML)
- Non-positioned elements (ordered by appearance in the HTML)
- Positioned elements (and their children) with a z-index value of
auto
(ordered by appearance in the HTML) - Positioned elements (and their children) with positive z-index values (higher values are stacked in front of lower values; elements with the same value are stacked according to appearance in the HTML
Global Stacking Order
With a firm understanding of how/when new stacking contexts are formed as well as a grasp of the stacking order within a stacking context, figuring out where a particular element will appear in the global stacking order isn’t so bad.
The key to avoid getting tripped up is being able to spot when new stacking contexts are formed. If you’re setting a z-index of a billion on an element and it’s not moving forward in the stacking order, take a look up its ancestor tree and see if any of its parents form stacking contexts. If they do, your z-index of a billion isn’t going to do you any good.