How to animate text on hover?

Hi,
I’m relatively new and have covered applied visual design in the FCC course.
I wanted to ask how do I animate text when hovering? I know one way to do is by using:hover but that doesnt include @keyframes ,so how would I(lets say) have the color of the text change gradually from white to black on hover?
Thanks for the help,

You can use the transition property for that. You specify the property that’s changing (color) and the time (0.5s).

.text-element {
  color:#fff;
  transition:color 0.5s;
}
.text-element::hover {
  color:#000;
}

You can also define a transition-timing-function to specify in which way the transition should happen: https://developer.mozilla.org/en-US/docs/Web/CSS/transition-timing-function

Thanks,
I’ll look more into this.

Also, Can I not use animations with :hover elements?

Actually, “:hover” is not an element but a “state” of an element. So you may just apply the transition properties to the original state of the element and it will work over all the other states.

Whoops,My bad.
Thanks for the info tho.

You can, if you give the element an infinitely running animation, and trigger the animation-play-state on hover:

.text-element {
    animation: change-color 1s infinite;
    animation-play-state: paused;
}
.text-element:hover {
    animation-play-state: running;
}
@keyframes change-color {
    0% {color:#fff;}
    100% {color:#000;}
}

The downside is that while you’re hovering, the text element will keep going from white to black over and over again, and remain in some grey state in-between when you stop hovering. It depends on your use case if this is doing what you’d like.

1 Like