How to Use animation-name in CSS for Animations
Use the
animation-name property in CSS to specify the name of the keyframes animation you want to apply to an element. This name links the element to a set of keyframes defined with @keyframes, controlling the animation sequence.Syntax
The animation-name property sets the name of the animation to apply. This name must match a @keyframes rule defined elsewhere in your CSS.
- animation-name: The identifier of the keyframes animation.
- none: Default value meaning no animation is applied.
css
selector {
animation-name: animationName;
}Example
This example shows a box that changes its background color smoothly using an animation named colorChange. The animation-name property links the box to the keyframes animation.
css
/* Define the animation steps */ @keyframes colorChange { 0% { background-color: red; } 50% { background-color: yellow; } 100% { background-color: green; } } /* Apply the animation to the box */ .box { width: 150px; height: 150px; animation-name: colorChange; animation-duration: 4s; animation-iteration-count: infinite; animation-timing-function: linear; }
Output
A square box that smoothly changes its background color from red to yellow to green repeatedly every 4 seconds.
Common Pitfalls
Common mistakes when using animation-name include:
- Not defining the
@keyframeswith the same name as theanimation-name. - Forgetting to set
animation-duration, so the animation does not run. - Using invalid or misspelled animation names.
Always ensure the keyframes name matches exactly and that duration is set.
css
/* Wrong: animation-name does not match keyframes name */ @keyframes slide { from { left: 0; } to { left: 100px; } } .element { animation-name: slideRight; /* No matching keyframes named slideRight */ animation-duration: 2s; } /* Correct: matching names */ .element { animation-name: slide; animation-duration: 2s; }
Quick Reference
| Property | Description | Example |
|---|---|---|
| animation-name | Name of the keyframes animation to apply | animation-name: fadeIn; |
| @keyframes | Defines the animation steps with the given name | @keyframes fadeIn { from {opacity: 0;} to {opacity: 1;} } |
| animation-duration | How long the animation lasts | animation-duration: 3s; |
| animation-iteration-count | How many times the animation repeats | animation-iteration-count: infinite; |
| animation-timing-function | Speed curve of the animation | animation-timing-function: ease-in-out; |
Key Takeaways
Use animation-name to link an element to a named @keyframes animation.
The animation-name value must exactly match the @keyframes name.
Always set animation-duration for the animation to run.
Common errors include mismatched names and missing duration.
Combine animation-name with other animation properties for full control.