What keyframes are
@keyframes in CSS is the standard way to define complex animations. Unlike transition, which only interpolates between two states, keyframes lets you define multiple intermediate stops and name the animation for reuse.
Basic syntax
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.element {
animation: fadeIn 0.5s ease-in-out;
} You can use from/to or percentages (0%, 50%, 100%). Percentages give finer control over intermediate stops.
Animations worth using
- fadeIn: smooth entrance for new elements.
- slideUp / slideDown: reveal from top or bottom.
- bounce: elastic bounce, useful to draw attention.
- pulse: heartbeat to indicate action or state.
- spin: continuous rotation, classic for loaders.
- shake: horizontal shake to flag an error.
Performance: animate what the GPU can composite
Browsers have three rendering stages: layout, paint, composite. Animating layout-affecting properties (width, height, top, left) recalculates positions and is slow. Animating opacity and transform only touches composite, which runs on the GPU. Difference: 60fps vs jank.
- Yes: opacity, transform (translate, scale, rotate).
- Careful: filter, color (paint).
- Avoid: width, height, padding, top, left (layout).
Easing
Easing is the acceleration curve. linear feels mechanical. ease-in-out is the pleasant default. cubic-bezier() lets you design custom curves: for "natural" motion try cubic-bezier(0.2, 0.8, 0.2, 1), popular in design systems like Material and iOS.
Animation shorthand
animation: name duration timing-function delay iteration-count direction fill-mode; Full example: animation: fadeIn 0.5s ease-in-out 0.2s 1 normal both;. fill-mode: both keeps the final state so the element does not "pop" back at the end.
Accessibility
Respect prefers-reduced-motion. Some people experience vertigo or vestibular issues with animations. Wrap your animations in this media query:
@media (prefers-reduced-motion: no-preference) {
.element { animation: fadeIn 0.5s; }
}