In many cases an element must be positioned for z-index
to work.
Indeed, applying position: relative
to the elements in the question would likely solve the problem (but there's not enough code provided to know for sure).
Actually, position: fixed
, position: absolute
and position: sticky
will also enable z-index
, but those values also change the layout. With position: relative
the layout isn't disturbed.
Essentially, as long as the element isn't position: static
(the default setting) it is considered positioned and z-index
will work.
Many answers to "Why isn't z-index working?" questions assert that z-index
only works on positioned elements. As of CSS3, this is no longer true.
Elements that are flex items or grid items can use z-index
even when position
is static
.
From the specs:
4.3. Flex Item Z-Ordering
Flex items paint exactly the same as inline blocks, except that order-modified document order is used in place of raw
document order, and z-index
values other than auto
create a stacking context even if position
is static
.
5.4. Z-axis Ordering: the z-index
property
The painting order of grid items is exactly the same as inline blocks, except that order-modified document order is
used in place of raw document order, and z-index
values other than auto
create a stacking context even if
position
is static
.
Here's a demonstration of z-index
working on non-positioned flex items: https://jsfiddle.net/m0wddwxs/
static
only to one element. We should ensure that we're applying the position property to all the elements being stacked on the basis of z-index else it doesn't work. – Exhibitor