DEV Community

Cover image for Stacking issues with z-index: Solved with isolate.
Haris Shah
Haris Shah

Posted on • Updated on

Stacking issues with z-index: Solved with isolate.

Recently, I was working on a project that has a card with a hover animation running from the bottom right side to the top left side.

hover effect
At first I created this effect using the HTML pseudo-element ::after and it worked with the position absolute, however, it covered all the content inside the card, which was not the effect I was going for.

effectcover

So I gave it the property of z-index: -1, but then the animation was behind the card and not visible.
To get it to work I removed the z-index value from ::after element and instead assigned z-index: 1; to all of the elements inside the card. This time the hover effect was showing up on the heading and img elements but not on the p element. Upon searching, I discovered that we have to make the p element position:relative. After I changed the p tag to position:relative, the effect displays perfectly.
But if we look at this approach, it is not good practice to change a lot of CSS to achieve this effect.

code Screenshot

Code before using isolate

Several days later, I was browsing YouTube when I saw a short video from Kevin Powell explaining the CSS property isolation:isolate. Watching that video, I was amazed at how easy it was to create this effect without writing much CSS.
The isolate property creates a new stacking context. When we declare the parent isolate, it locks the content inside it. Now if we make the ::after element z-index of -1 it will be only negative to its siblings not the entire container!
I removed all z-indexes from card elements and declared only one CSS property isolate on the card.

after using isolate

after
We can now see that the code is much cleaner and does not have any additional side effects.

Thanks for reading this. Please do share your feedback & suggestions in the comments section.

Top comments (3)

Collapse
 
khojo_kwofie profile image
Evans Kojo Kwofie

Thanks for sharing this tip. I most definitely did not know about the isolate property.

Collapse
 
hariscs profile image
Haris Shah

thanks for reading it.

Collapse
 
iambilalriaz profile image
Hafiz Muhammad Bilal

Keep the good work up @_haris_shah