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
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); } }
- Create a
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 thepulse
animation 3 times, with each cycle lasting 2 seconds.
- Use the
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
to360deg
.
- Defines an animation that rotates the element from
.rotating-box
:- The
animation-name
property applies therotate
animation. - The
animation-duration
property sets the duration of one rotation cycle to 4 seconds. - The
animation-iteration-count
property is set toinfinite
, so the rotation will continue endlessly.
- The
Important Points
Default Value:
- The default value for
animation-iteration-count
is1
, which means the animation will run only once if not otherwise specified.
- The default value for
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.
Usage with Animation Delay:
animation-iteration-count
works in conjunction withanimation-delay
. You can set a delay for the animation to start and specify how many times it should repeat.