How to Use animation-duration in CSS for Smooth Animations
Use the
animation-duration property in CSS to set how long an animation takes to complete one cycle. You specify the time in seconds (s) or milliseconds (ms), like animation-duration: 2s; for a 2-second animation.Syntax
The animation-duration property defines the length of time an animation takes to complete one cycle. You set it using a time value in seconds (s) or milliseconds (ms).
- Value: Time (e.g.,
2s,500ms) - Default:
0s(animation does not play)
css
animation-duration: <time>;
Example
This example shows a square that changes its background color smoothly over 3 seconds using animation-duration.
css
html, body {
height: 100%;
margin: 0;
display: flex;
justify-content: center;
align-items: center;
background: #f0f0f0;
}
.box {
width: 150px;
height: 150px;
background-color: #3498db;
animation-name: colorChange;
animation-duration: 3s;
animation-iteration-count: infinite;
animation-direction: alternate;
}
@keyframes colorChange {
from { background-color: #3498db; }
to { background-color: #e74c3c; }
}Output
<div style="display:flex;justify-content:center;align-items:center;height:150px;width:150px;background-color:#3498db;animation-name:colorChange;animation-duration:3s;animation-iteration-count:infinite;animation-direction:alternate;"></div>
Common Pitfalls
Common mistakes when using animation-duration include:
- Setting the duration to
0sor forgetting to set it, which stops the animation from playing. - Using invalid time units or values (like just numbers without
sorms). - Not combining
animation-durationwith other animation properties likeanimation-name, so the animation does not run.
css
/* Wrong: Missing time unit, animation won't run */ .box { animation-name: slide; animation-duration: 3; /* Missing 's' or 'ms' */ } /* Correct: Include time unit */ .box { animation-name: slide; animation-duration: 3s; }
Quick Reference
| Property | Description | Example |
|---|---|---|
| animation-duration | Sets how long one animation cycle lasts | animation-duration: 2s; |
| animation-name | Specifies the animation to use | animation-name: fadeIn; |
| animation-iteration-count | Number of times animation repeats | animation-iteration-count: infinite; |
| animation-direction | Direction of animation cycles | animation-direction: alternate; |
Key Takeaways
Always specify a time unit (s or ms) with animation-duration.
animation-duration controls how long one animation cycle takes.
Combine animation-duration with animation-name to see the effect.
A duration of 0s means the animation won't play.
Use animation-iteration-count to repeat animations smoothly.