Transitioning gradients

Hello! I recently discovered that it isn’t possible to directly create a transition using gradients, but I found two ways to do it:


These have worked so far but there’s a few things I don’t understand (I’m still a beginner!):

  1. why do we need the direction (top, right, bottom, left) properties with ::before?
  2. for the second link, I don’t really understand how .gradient::before and .gradient:hover::before work together. why are we not using .gradient:hover::after? it doesn’t make sense.
  3. what role does the z-index play in this case?
  4. is there a way we can do this without the :hover?
  5. is there a way to make the transition repeat itself?

i know i’m probably asking for a lot, but if you could answer just one of the questions, i’d really appreciate it. thank you so much!

Hey @raida, so I’m a beginner too (about a month in!), and I haven’t really messed with the :before and :after pseudoclasses yet other than what was in the challenges. So I can’t really say much about those until I look at them a it deeper.

But I found the problem interesting and my immediate thought was to use @keyframes to animate a transition. You can check it out here:

I have to say, it’s a different transition effect that I’ve ended up coming up with than yours is, so I guess it depends on the specific effect you’re looking for as to which method you would choose. I really like your effect though, I’d like to maybe try and integrate it into one of my projects.

Thanks for the challenge, it was fun! I hope I helped a bit!

  1. Because it is using position absolute and to make it fill the full height and width of it’s relatively positioned parent element (::before and ::after are children of the element they are set on). In the first example, you don’t really need it because the height and width are being set, but in general, it is never a bad idea to set the top and left and some just do it out of habit I think.

  2. Not sure there really is a reason for it in this case other than ::before being the first pseudo-element so it comes before the content.

DOM layout:

<div class="gradient">
  <a href="#">test to verify content remains visible &amp; on top</a>

<div class="gradient">
  <a href="#">test to verify content remains visible &amp; on top</a>
  1. It makes it so you can still see the content inside the parent element (i.e. the text “test to verify content remains visible & on top”) when hovering.

4/5. CSS animations can run on their own and you can loop them however many times you want.