How to Use animation-delay in CSS for Smooth Animations
Use the
animation-delay property in CSS to set a time delay before an animation starts. It accepts time values like 2s or 500ms, allowing you to control when the animation begins after the element loads or is triggered.Syntax
The animation-delay property defines how long to wait before starting the animation. It accepts a time value in seconds (s) or milliseconds (ms).
- animation-delay: time value (e.g.,
2s,500ms) - Can be negative to start the animation partway through
css
animation-delay: 2s; animation-delay: 500ms; animation-delay: -1s;
Example
This example shows a box that changes color with a 2-second delay before the animation starts.
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: changeColor;
animation-duration: 3s;
animation-delay: 2s;
animation-fill-mode: forwards;
}
@keyframes changeColor {
from { background-color: #3498db; }
to { background-color: #e74c3c; }
}Output
A blue square appears centered on the page. After 2 seconds, it smoothly changes its color to red over 3 seconds.
Common Pitfalls
Common mistakes when using animation-delay include:
- Not setting
animation-fill-mode, so the element snaps back after animation ends. - Using negative delays without understanding they start the animation partway through.
- Forgetting to specify units like
sorms, which makes the value invalid.
css
/* Wrong: missing units */ .box { animation-delay: 2; /* invalid, no units */ } /* Right: with units */ .box { animation-delay: 2s; animation-fill-mode: forwards; }
Quick Reference
| Property | Description | Example |
|---|---|---|
| animation-delay | Time to wait before animation starts | animation-delay: 1.5s; |
| animation-fill-mode | Defines styles after animation ends | animation-fill-mode: forwards; |
| animation-duration | Length of the animation | animation-duration: 3s; |
| Negative delay | Starts animation partway through | animation-delay: -1s; |
Key Takeaways
Use
animation-delay to control when an animation starts by specifying a time value with units.Always include units like
s or ms to avoid invalid CSS.Combine
animation-delay with animation-fill-mode: forwards to keep the final animation state visible.Negative
animation-delay values start the animation partway through, which can be useful for syncing animations.Test animations in the browser to see the delay effect clearly.