What does the z-index property do?
z-index controls the stacking order of elements along the Z axis, that is, it determines which element appears on top of others when they overlap.
It only works for elements that create a stacking context: usually these are elements with a position other than static (relative, absolute, fixed, sticky), along with a number of other conditions.
How it works
- the higher the value of
z-index, the closer the element is to the user (higher in the layers) - elements with the same
z-indexare ordered by DOM order z-indexdoes not work on elements withposition: static
Example
css
.box1 {
position: absolute;
z-index: 1;
}
.box2 {
position: absolute;
z-index: 10;
}.box2 will be on top of .box1.
When z-index does not work
Even if you set a higher value, the element may not rise if it is:
- in a different stacking context
- has no positioning
- "trapped" by a parent that has its own context (for example,
transform,opacity,filter,isolation,z-index: 0, etc.)
Summary
z-index controls the stacking depth of elements, but its effect is limited to stacking contexts.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.