Skip to main content
CSS animations provide a declarative way to create smooth, performant animations without JavaScript. They’re ideal for simple transitions and looping animations.

Keyframe definitions

Keyframes define the states of your animation at specific points in time. Here are real examples from the Animation Playground:
@keyframes fade-in {
  0% { opacity: 0; }
  100% { opacity: 1; }
}

Animation properties

Duration

Controls how long one animation cycle takes to complete:
.element {
  animation-duration: 1s;     /* 1 second */
  animation-duration: 2s;     /* 2 seconds */
  animation-duration: 500ms;  /* 500 milliseconds */
}

Timing function

Controls the acceleration curve of the animation:
.element {
  animation-timing-function: linear;
  /* Constant speed throughout */
}

Iteration count

Defines how many times the animation repeats:
.element {
  animation-iteration-count: 1;        /* Plays once */
  animation-iteration-count: 3;        /* Plays 3 times */
  animation-iteration-count: infinite; /* Loops forever */
}

Direction

Controls whether the animation plays forward, backward, or alternates:
.element {
  animation-direction: normal;
  /* Always plays forward */
}

Complete examples

Here’s how to combine all properties together:
.element {
  animation: fade-in 1s ease infinite alternate;
}

@keyframes fade-in {
  0% { opacity: 0; }
  100% { opacity: 1; }
}

Animation control

You can pause and resume animations with JavaScript:
const getAnimationStyle = () => {
  return {
    animationName: 'fade-in',
    animationDuration: '1s',
    animationTimingFunction: 'ease',
    animationIterationCount: 'infinite',
    animationDirection: 'alternate',
    animationPlayState: isPaused ? 'paused' : 'running'
  }
}

Best practices

  • Use transform and opacity for the best performance
  • Avoid animating width, height, or margin as they trigger layout recalculation
  • Keep animations under 300ms for UI feedback
  • Use will-change sparingly to hint at upcoming animations
  • Test on lower-end devices to ensure smooth playback

When to use CSS animations

CSS animations are ideal for:
  • Simple looping animations
  • Hover and focus states
  • Loading spinners and indicators
  • Entrance and exit animations
  • Animations that don’t require dynamic values
For more complex scenarios involving user interaction or dynamic calculations, consider JavaScript animations instead.

Build docs developers (and LLMs) love