Keyframes, Animation Timeline & prefers-reduced-motion

Keyframes, Animation Timeline & prefers-reduced-motion in CSS: While transitions interpolate between an initial state and a final state triggered by an…

While transitions interpolate between an initial state and a final state triggered by an interaction (like :hover), @keyframes allow complex multi-step sequences that run automatically or on loops.


Defining Multi-Stage Keyframes

@keyframes pulseGlow {
  0% {
    transform: scale(0.96);
    box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.7);
  }
  70% {
    transform: scale(1.02);
    box-shadow: 0 0 0 14px rgba(59, 130, 246, 0);
  }
  100% {
    transform: scale(0.96);
    box-shadow: 0 0 0 0 rgba(59, 130, 246, 0);
  }
}

.status-badge-live {
  animation: pulseGlow 2.5s infinite cubic-bezier(0.4, 0, 0.6, 1);
}

The Animation Shorthand Breakdown

.element {
  /* animation: [name] [duration] [timing-function] [delay] [iteration-count] [direction] [fill-mode] */
  animation: slideIn 400ms cubic-bezier(0.16, 1, 0.3, 1) 100ms 1 normal forwards;
}
  • animation-fill-mode: forwards: Ensures the element retains the styles calculated at the end of the animation (100%) rather than snapping back to its pre-animated state.
  • animation-iteration-count: infinite: Loops continuously.

Accessibility: prefers-reduced-motion

Many users suffer from vestibular disorders where rapid movement, parallax scrolling, or scaling animations cause motion sickness or vertigo. Operating systems provide a "Reduce Motion" setting.

Production websites MUST respect this setting:

@media (prefers-reduced-motion: reduce) {
  *, *::before, *::after {
    animation-duration: 0.01ms !important;
    animation-iteration-count: 1 !important;
    transition-duration: 0.01ms !important;
    scroll-behavior: auto !important;
  }
}

Cutting-Edge: Scroll-Driven Animations

Modern CSS allows linking an animation's progress directly to the page's scroll position without JavaScript scroll event listeners:

/* Reading Progress Bar at the top of the screen */
@keyframes growProgressBar {
  from { transform: scaleX(0); }
  to   { transform: scaleX(1); }
}

.reading-progress-bar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 4px;
  background-color: var(--color-brand);
  transform-origin: left;
  
  /* Binds animation progress directly to document scroll! */
  animation: growProgressBar auto linear;
  animation-timeline: scroll(root);
}

Exercises

  1. Build a skeleton loading animation with a continuous shimmering gradient effect using @keyframes.
  2. Implement a scroll-driven reading progress bar that fills as the user scrolls down an article.
  3. Test your website with prefers-reduced-motion enabled in Chrome DevTools Rendering settings.