Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Resume and pause animations in CSS

I have been working with CSS for like 10+ years now and I have worked with CSS animations for a fair amount of time. But I didn’t know that you can pause and resume animations in CSS until recently.

Essentially, you can pause and resume animations in CSS using the animation-play-state property. This property accepts two values: running and paused.

The running value is the default value and it lets the animation run as normal. The paused value pauses the animation.

This can help you build some interesting UIs. For instance, you can pause the animation when the user hovers over the element and resume it when the user hovers out of the element.

Or turn it off on a button click and turn it on again when the user clicks the button again.

Here’s an example of the same.

.container {
  display: flex;
  height: 100%;
  background: linear-gradient(
    to right,
    #7953cd 20%,
    #00affa 30%,
    #0190cd 70%,
    #764ada 80%
  );
  background-size: 500% auto;
  animation: animatedGradient 3s ease-in-out infinite;
  animation-play-state: running;
}

.container:hover {
  animation-play-state: paused;
}

@keyframes animatedGradient {
  0% {
    background-position: 0% 50%;
  }
  100% {
    background-position: 100% 50%;
  }
}

As you can tell, the animatedGradient animation will be paused when the user hovers over the .container element and resumes when the user hovers out of the element.

Here’s a CodePen to play with.

See the Pen Animated gradient effect using CSS by Amit Merchant (@amit_merchant) on CodePen.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?