0
0
CssHow-ToBeginner · 3 min read

How to Use animation-iteration-count in CSS for Repeating Animations

Use the animation-iteration-count CSS property to specify how many times an animation should repeat. You can set it to a number (like 3) for a fixed count or infinite to loop endlessly.
📐

Syntax

The animation-iteration-count property accepts either a positive number or the keyword infinite. It controls how many times the animation runs.

  • number: Runs the animation that many times (e.g., 3).
  • infinite: Runs the animation endlessly.
css
animation-iteration-count: 3;
animation-iteration-count: infinite;
💻

Example

This example shows a square that changes color three times and then stops.

css
/* CSS */
@keyframes colorChange {
  0% { background-color: red; }
  50% { background-color: yellow; }
  100% { background-color: green; }
}

.box {
  width: 100px;
  height: 100px;
  background-color: red;
  animation-name: colorChange;
  animation-duration: 3s;
  animation-iteration-count: 3;
  animation-fill-mode: forwards;
}
Output
A 100x100 pixel square that smoothly changes from red to yellow to green, repeating this color change 3 times, then stays green.
⚠️

Common Pitfalls

Common mistakes include:

  • Using a negative number or zero, which is invalid and ignored.
  • Forgetting to set animation-duration, so the animation does not run visibly.
  • Not using animation-fill-mode: forwards; if you want the animation to keep its last state after finishing.
css
/* Wrong: negative count ignored */
.box {
  animation-iteration-count: -1; /* ignored */
  animation-duration: 2s;
}

/* Right: positive count */
.box {
  animation-iteration-count: 1;
  animation-duration: 2s;
}
📊

Quick Reference

ValueDescription
number (e.g., 1, 3, 5)Runs the animation that many times
infiniteRuns the animation endlessly
initialSets to default (1)
inheritInherits from parent element

Key Takeaways

Use animation-iteration-count to control how many times an animation repeats.
Set it to a number for fixed repeats or infinite for endless looping.
Always specify animation-duration for the animation to run.
Use animation-fill-mode: forwards; to keep the animation's final state.
Avoid negative or zero values as they are invalid and ignored.