Z-index not working – troubleshooting

The Z-index property can be strange at times. If you don’t have much experience with using it, you might find that it only works most of the time when you need it 100% of the time. Fortunately for you, it isn’t the Z-Index’s fault and there are actually some ways to explain its malfunctions. Here are two common problems that could be causing a headache-inducing Z-Index bug.

1) Not specifying a position for an element.

The Z-Index property will simply not work if there isn’t a specific positioning for an element that isn’t static. For example, there are two <div> tags. They both are left as static because they don’t need any fancy additional positioning. The project requires the <div> that is underneath the other to be raised to a higher Z-Index, but when the lower <div> is given the Z-Index property with a higher numeric value nothing seems to happen. This is because the Z-Index does not work with static positioning. Z-Index requires an element’s positioning to be either fixed, relative, or absolute. Judging based on how many times this question has been asked, it is safe to say that this is the most common problem people have with the Z-Index function.

2) Stacking Contexts.

With the Z-Index property there is this poorly documented thing called stacking contexts. Normally an element with a higher Z-Index gets placed above elements with lower Z-Indexes, following common logic. However; stacking contexts can change this in certain circumstances.

Imagine a stack of sheets of paper with drawings on them. The pieces of paper can be rearranged, and the drawings on them can be too, but a drawing on a lower sheet of paper cannot be higher than a drawing on a higher sheet of paper.

This is essentially how stacking contexts work. To translate this into HTML/CSS terms, replace the sheets of paper with parent elements and the drawings with child elements. If a parent element is positioned below another parent element, then the child elements cannot go higher than an element positioned higher than their parent element. Keep this in mind when using the Z-Index.

Wrapping Up:

The Z-Index property is a powerful tool to arrange elements, but stacking contexts must be considered first. They aren’t as well documented as they should be for such a vital part of Z-Index which makes them tricky for a lot of developers.

Also, remember the basics. Do not use the Z-Index without specifying a position for an element. It will not work!