Sometimes, CSS doesn’t behave in quite the way we expect it to. Take CSS animations, for example: After creating one, you may want your animation to loop over and over.
However, that’s not what happens. By default, an animation will occur once, then stop. So, what if we want our animation to repeat several times, or infinitely for something like a loading animation? To do that, we’ll need to set a number of iterations with the animation-iteration-count property.
It might have one of the longer names among CSS properties, but animation-iteration-count isn’t too difficult to understand, and once you know how it works you can create repeating animations to engage page viewers. Let’s take a closer look.
What is animation-iteration-count?
The animation-iteration-count CSS property specifies how many times an animation sequence will play. If the iteration count is finite, the animation will stop after the specified number of cycles. The rule is written as follows:
The animation-iteration-count property can take several values. Its main values are infinite and <number>, and the property also accepts the global values initial and inherit. Let’s go through each one now.
If assigned an animation-iteration-count value of infinite, the animation will repeat infinitely. This is the best value for an animation that you don’t want stopping on its own.
The initial value sets the value of animation-iteration-count to its default, 1.
If inherit is specified, animation-iteration-count will inherit the value from the parent element.
Multiple Values for animation-iteration-count
In the above examples, we’ve assigned just one value to animation-iteration-count, but this property (as well as other CSS animation properties) can handle multiple values as well. This allows you to assign different iteration counts to different animations.
To add multiple values to animation-iteration-count, add values separated by commas, like so:
animation-iteration-count: 3, 5, infinite;
Listing multiple values for animation-iteration-count (and other CSS animation properties) assigns each value to a value listed with the animation-name property based on the order of the list. The first value of animation-iteration-count applies to the first value of animation-name, the second value of animation-iteration-count applies to the second value of animation-name, and so on.
With just an extra line of CSS, it’s easy to make your animations loop infinitely for a specified number of iterations. For example, you could apply some subtle movement to make an element appear to “hover” on the page, or apply a fun shaking effect to a button click. You have extensive control over your animations and styling, which is what CSS is all about.
Originally published Aug 4, 2021 7:00:00 AM, updated August 24 2021