CSS animations are a powerful tool for creating dynamic and engaging web experiences. They allow you to animate elements on your page without the need for JavaScript or complex libraries.
However, writing CSS animations can be verbose and repetitive, especially when you have multiple keyframes and properties to define.
These are the properties the shorthand animation property takes in order:
- N: Name
- D: Duration
- T: Timing function
- D: Delay
- I: Iteration count
- D: Direction
- F: Fill mode
- P: Play state
For example you could have:
animation: name duration timing-function delay iteration-count direction fill-mode play-state;
/* And a couple of examples with all 8 properties */
.element {
animation: bounce 2s ease-in-out 0.5s 3 alternate-reverse both running;
/* | | | | | | | |
| | | | | | | └─ Play state: running
| | | | | | └───── Fill mode: both
| | | | | └──────────────────── Direction: alternate-reverse
| | | | └────────────────────── Iteration count: 3
| | | └─────────────────────────── Delay: 0.5s
| | └─────────────────────────────────────── Timing function: ease-in-out
| └─────────────────────────────────────────── Duration: 2s
└───────────────────────────────────────────────── Name: bounce
*/
}
/* Alternative example - paused animation */
.paused-element {
animation: fadeIn 1s linear 0s 1 normal forwards paused;
/* | | | | | | | |
| | | | | | | └─ Play state: paused
| | | | | | └─────────── Fill mode: forwards
| | | | | └────────────────── Direction: normal
| | | | └──────────────────── Iteration count: 1
| | | └─────────────────────── Delay: 0s (no delay)
| | └────────────────────────────── Timing function: linear
| └───────────────────────────────── Duration: 1s
└──────────────────────────────────────── Name: fadeIn
*/
}
Now you might find it hard to remember the order these properties come in, or just all the available CSS animation options for that matter. Here’s a simple mnemonic to help you remember the order of properties in the CSS animation shorthand:
Nancy Drinks Tea During Intense Dance For Peace
By following this mnemonic, you can quickly and easily write CSS animations without having to look up the order of properties each time. This can save you time and make your code more readable and maintainable.
Example
Here’s an example of a simple CSS animation using the shorthand syntax:
@keyframes bounce {
0%,
100% {
transform: translateY(0);
}
50% {
transform: translateY(-20px);
}
}
.element {
animation: bounce 1s ease-in-out 1s infinite alternate both paused;
}
Note on animation-timeline
The animation-timeline property is a newer addition for scroll-driven animations, but it’s not part of the standard animation shorthand and must be declared separately. It has limited browser support and is still considered experimental.