Back to all posts

Scroll-driven animations with nothing but CSS

For years, scroll-linked effects meant a scroll event listener, a requestAnimationFrame loop and a lot of care to avoid layout thrashing. Scroll-driven animations move that work into the browser: you write normal @keyframes, then tell the browser that the animation's progress comes from scrolling instead of time.

Two kinds of timeline

  • scroll() follows the scroll position of a container, from top to bottom. A reading-progress bar is the classic example.
  • view() follows an element as it travels through the viewport. Use it for reveals, parallax and anything that reacts to an element entering the screen.

A reading-progress bar in six lines

css
.progress {
  position: fixed; inset: 0 0 auto 0; height: 3px;
  transform-origin: left;
  animation: grow linear both;
  animation-timeline: scroll(root);
}
@keyframes grow { from { transform: scaleX(0); } to { transform: scaleX(1); } }

Because the animation only touches transform, it runs on the compositor and stays smooth even when the main thread is busy.

Reveal elements as they enter

css
.card {
  animation: reveal linear both;
  animation-timeline: view();
  animation-range: entry 0% cover 30%;
}
@keyframes reveal {
  from { opacity: 0; translate: 0 2rem; }
  to   { opacity: 1; translate: 0 0; }
}

animation-range decides which slice of the element's journey drives the animation. entry 0% cover 30% means: start when the element first peeks in, finish when it is about a third of the way up the screen.

Ship it as progressive enhancement

Not every browser supports scroll timelines yet, so wrap them in a feature query and respect users who have asked for less motion. Everyone gets the content; supporting browsers get the motion.

css
@supports (animation-timeline: view()) {
  @media (prefers-reduced-motion: no-preference) {
    .card { /* animation rules here */ }
  }
}
The best scroll animation is one that explains the page. If it only decorates, cut it.