CSS Animations
Animations
CSS animations let you animate property values over time without user interaction (unlike transitions which typically depend on a state change such as :hover).
An animation requires:
- a
@keyframesrule (the steps of the animation) - an
animationdeclaration (how the animation runs)
Basic example:
.box {
animation: fade-in .4s ease;
}
Keyframes
@keyframes defines the animation steps. You can use from/to or percentages.
@keyframes fade-in {
from { opacity: 0; }
to { opacity: 1; }
}
Using percentages gives you more control:
@keyframes bounce {
0% { transform: translateY(0); }
40% { transform: translateY(-12px); }
70% { transform: translateY(0); }
100% { transform: translateY(0); }
}
Tip: Animating transform and opacity is usually smoother and more performant than animating layout properties like top, left, width, or height.
Animation Properties
The shorthand animation can include these parts:
animation-nameanimation-durationanimation-timing-functionanimation-delayanimation-iteration-countanimation-directionanimation-fill-modeanimation-play-state
Example (shorthand):
.loader {
animation: spin 1s linear infinite;
}
Example (separate properties):
.badge {
animation-name: pulse;
animation-duration: 900ms;
animation-timing-function: ease-in-out;
animation-iteration-count: infinite;
animation-direction: alternate;
}
fill-mode controls what styles apply before/after the animation:
none– defaultforwards– keeps the final statebackwards– applies the first keyframe during delayboth– forwards + backwards
.toast {
animation: slide-in .25s ease forwards;
}
Common Patterns
1) Spinner (rotation)
@keyframes spin {
to { transform: rotate(360deg); }
}
.spinner {
width: 36px;
height: 36px;
border: 4px solid rgba(0,0,0,.15);
border-top-color: rgba(0,0,0,.65);
border-radius: 50%;
animation: spin 1s linear infinite;
}
2) Pulse (attention effect)
@keyframes pulse {
from { transform: scale(1); opacity: 1; }
to { transform: scale(1.06); opacity: .75; }
}
.pulse {
display: inline-block;
animation: pulse .9s ease-in-out infinite alternate;
}
3) Slide in (UI panels/toasts)
@keyframes slide-in {
from { transform: translateY(10px); opacity: 0; }
to { transform: translateY(0); opacity: 1; }
}
.toast {
animation: slide-in .25s ease forwards;
}
Accessibility tip: Respect reduced motion preferences by disabling or simplifying animations when users request it.
@media (prefers-reduced-motion: reduce) {
* {
animation: none !important;
transition: none !important;
scroll-behavior: auto !important;
}
}
Summary
- Animations run using
@keyframes+animationproperties. - Prefer animating
transformandopacityfor smooth motion. - Use
fill-modeto keep the final state when needed. - Use
prefers-reduced-motionfor accessibility.