Control the Speed of Infinite Animations in CSS

Control the Speed of Infinite Animations in CSS

Infinite animations are everywhere in modern web design. From spinning loading icons to endless marquee text sliders, they add life and dynamism to a static page. But there is a common problem developers face: how do you effectively control the speed of these animations without constantly rewriting your CSS?

In this quick tutorial, we are going to explore how to master infinite CSS animations by leveraging CSS custom properties (variables) to make your animation speeds dynamic and highly interactive.

1. The Standard Infinite Animation

Traditionally, developers hardcode the animation duration directly into the CSS rule. While this works, it’s rigid. If you want a fast version and a slow version of the same animation, you end up writing duplicate code.

.box { animation: spin 5s linear infinite;
}
@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); }
}

2. The Smart Way: Using CSS Variables

By replacing the hardcoded 5s with a CSS variable, you unlock the ability to change the speed instantly across multiple elements or dynamically via JavaScript.

.box { /* Default speed is 5 seconds */ --speed: 5s; animation: spin var(--speed) linear infinite;
}
.box.fast { /* Instantly speeds up the animation */ --speed: 1s;
}
.box.slow { /* Slows down the animation */ --speed: 15s;
}

This approach keeps your code incredibly DRY (Don’t Repeat Yourself) and makes maintaining massive CSS files much easier.

3. Pausing the Animation on Hover

A great user experience rule of thumb is to give users control. If you have an infinite scrolling ticker or an orbiting element, it’s best practice to pause the animation when the user hovers over it so they can interact with it.

We can achieve this beautifully using animation-play-state:

.box:hover { animation-play-state: paused; cursor: pointer;
}

The Bottom Line

CSS animations don’t have to be rigid. By injecting CSS variables into your animation shorthand properties, you can easily control the speed, delay, and behavior of infinite animations dynamically. Combined with animation-play-state, you can create highly interactive and accessible components in just a few lines of code.

What do you think? Have you started using CSS variables to control your animations yet? Let us know in the comments below!

Comments

No comments yet. Why don’t you start the discussion?

    Leave a Reply

    Your email address will not be published. Required fields are marked *