Codectionary / Developer documentation / CSS

Animations & @keyframes

@keyframes defines a named sequence of styles at different points (0% to 100%) of an animation, which is then applied to an element via the animation property. Unlike transitions, which only animate between two states, keyframe animations can define arbitrarily complex multi-step sequences and loop indefinitely.

Syntax

@keyframes name { 0% { } 100% { } }
animation: name duration timing-function iteration-count;

Examples

A Basic Keyframe Animation

Defining and applying a fade-in-and-rise animation.

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.card {
  animation: fadeInUp 0.5s ease-out;
}

Multi-Step and Looping Animation

A pulsing loading indicator using percentage-based keyframes.

@keyframes pulse {
  0%, 100% { opacity: 1; transform: scale(1); }
  50% { opacity: 0.5; transform: scale(1.1); }
}

.loading-dot {
  animation: pulse 1.5s ease-in-out infinite;
}

Parameters and values

  • animation-name (identifier): References a @keyframes rule by name
  • animation-duration (time): Length of one animation cycle
  • animation-iteration-count (number | infinite): How many times the animation repeats
  • animation-fill-mode (none | forwards | backwards | both): What styles apply before/after the animation runs

Best practices

  • Use @keyframes for multi-step or looping animations, and simple transitions for animating between exactly two states
  • Set animation-fill-mode: forwards when the animation's end state should persist after it finishes, rather than snapping back to the original style
  • Use infinite only for genuinely continuous effects like loading spinners - most UI animations should run once
  • Wrap non-essential animations in an @media (prefers-reduced-motion: no-preference) query so users with motion sensitivity are not affected

At a glance

Purpose
Presentation and layout
File extension
.css
Runs in
Web browsers
Usually used with
HTML and JavaScript

Specifications & further reading

Related CSS documentation