CSS PSEUDO-ELEMENT STACKING

SETTING THE STACKING ORDER OF PSEUDO-ELEMENTS BELOW THEIR PARENT ELEMENT

-

Dec 18, 2018

When you use the :before and :after pseudo-elements to display content behind their parent element, you often find that this content gets displayed on top of the parent, even though you’ve set z-index:-1. And when it works, it may fail when you nest instances of the parent element. Here’s why.

It is important to realize that pseudo-elements are considered descendants of their associated element. You may set a negative z-index for these pseudo-elements, but in order for them to actually appear below their parent element, you must create a new stacking context for the parent.

The above code can be made to work by removing the z-index from the parent element. However, this will still fail when you nest multiple elements, because then the stacking context is no longer correct.

The trick to making this work is by creating a stacking context on a container element around the parent element. This container elements must have a position, as well as a z-index.