CSS animation-iteration-count property


The animation-iteration-count property in CSS specifies the number of times an animation should repeat. This property determines how many times the animation runs before stopping. It can be set to a specific number of iterations or to infinite for an endless loop.

Syntax

element { animation-iteration-count: count; }
  • count: Defines how many times the animation should repeat. It can be:
    • A specific number: Defines the exact number of times the animation will repeat.
    • infinite: The animation will repeat indefinitely.

How It Works

  1. Define the Keyframes:

    • Create a @keyframes rule that defines the stages of the animation.
    @keyframes pulse { 0% { transform: scale(1); } 50% { transform: scale(1.5); } 100% { transform: scale(1); } }
  2. Apply the Animation:

    • Use the animation-iteration-count property to specify how many times the animation should repeat.
    .pulsing-box { width: 100px; height: 100px; background-color: red; animation-name: pulse; animation-duration: 2s; animation-iteration-count: 3; }
    • In this example, the .pulsing-box element will perform the pulse animation 3 times, with each cycle lasting 2 seconds.

Example

HTML

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Animation Iteration Count Example</title> <style> @keyframes rotate { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } .rotating-box { width: 100px; height: 100px; background-color: blue; animation-name: rotate; animation-duration: 4s; animation-iteration-count: infinite; } </style> </head> <body> <div class="rotating-box"></div> </body> </html>

Explanation:

  • @keyframes rotate:

    • Defines an animation that rotates the element from 0deg to 360deg.
  • .rotating-box:

    • The animation-name property applies the rotate animation.
    • The animation-duration property sets the duration of one rotation cycle to 4 seconds.
    • The animation-iteration-count property is set to infinite, so the rotation will continue endlessly.

Important Points

  1. Default Value:

    • The default value for animation-iteration-count is 1, which means the animation will run only once if not otherwise specified.
  2. Multiple Animations:

    • If you have multiple animations applied to an element, you can set different iteration counts for each by separating them with commas.
    element { animation-name: fadeIn, slideIn; animation-duration: 2s, 3s; animation-iteration-count: 1, infinite; }
    • In this case, the first animation (fadeIn) will run once, while the second animation (slideIn) will repeat indefinitely.
  3. Usage with Animation Delay:

    • animation-iteration-count works in conjunction with animation-delay. You can set a delay for the animation to start and specify how many times it should repeat.