Create a smooth transition from one gradient to another
Have you ever tried to slowly transition from one gradient background to another on hover? You might have quickly realized that it's not possible to do so with the CSS transition
property on background-image
. But isn't this a nice effect?
It would be great if we could simply do this using the transition property:
But this doesn't animate. The background immediately switches from one gradient to another.
Here's a little hack
We can use ::before
to add a pseudo element just within the .gradient
element. Then we make this pseudo element fill up the entire space of the .gradient
using position: absolute
and inset: 0
To the .gradient
element we set our initial gradient background. To the pseudo element we set out final gradient background.
The most important step is to set opacity: 0
to our pseudo element to start with. On hover, we can use the transition
property and change that opacity
to 1. We know that transition animation works for opacity. So we have achieved the desired result 🥳
Just one problem
The background animation works. But there's just one problem. If you have a text within this background (which you obviously will), that gets hidden on hover! This happens because the pseudo element is absolutely positioned, so it gets placed one layer on top of the text.
How do we fix that? You guessed it right - With z-index
like so.
The pseudo element needs to have a z-index
of -1
to make the text visible. And the .gradient
element needs to have a higher z-index
, otherwise you cannot "hover" over it.
This issue is inspired by this write-up: https://keithjgrant.com/posts/2017/07/transitioning-gradients/
Hope you enjoyed reading this :) Let me know!
📘 Complete Guide to CSS Flex and Grid
If you loved this write-up and how it was explained, you’ll absolutely love my eBook CSS Flex and Grid. Check it out!
📨 Newsletter suggestion
I love Tailwind CSS. If you love it too, I highly recommend subscribing to this one 👇
Tailwind Weekly: Weekly newsletter about all things Tailwind CSS. New issue every Saturday.