Skip to content
Scroll-Driven Animations & View Transitions: Two Lines of CSS, Zero Main-Thread Work

Scroll-Driven Animations & View Transitions: Two Lines of CSS, Zero Main-Thread Work

This guide shows how to replace JavaScript scroll listeners and manual FLIP animations with CSS animation-timeline and View Transitions API, enabling performant scroll progress bars, entrance animations, and cross-page transitions that run entirely on the compositor thread, with progressive enhancement and accessibility fallbacks.

Code Farmer Manor Chronicle
Code Farmer Manor Chronicle
Code Farmer Manor Chronicle

Scroll-Driven Animations: Why the Browser Must Handle Them

The traditional approach of listening to scroll events on the main thread suffers from a timing mismatch: scrolling occurs on the compositor thread, but reading scrollY and updating styles forces layout and paint on the main thread. When the main thread is busy, the progress bar stalls while the page continues scrolling. animation-timeline moves the animation timeline to scroll progress, letting the compositor compute frames directly. A scroll progress bar becomes two lines of CSS:

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

The scroll() function accepts four variants: scroll(root) for the whole page, scroll(nearest) for the nearest scrolling ancestor, scroll(self) for the element itself, and scroll(--my-timeline) for a named timeline.

view() for Entrance Animations

view()

drives animations based on an element crossing the viewport. The animation runs from the moment the element enters until it is fully inside, and reverses when scrolling back — no IntersectionObserver or once flag needed because the timeline is continuous and bidirectional.

.card {
  animation: rise linear both;
  animation-timeline: view();
  animation-range: entry 0% entry 60%;
}
@keyframes rise {
  from { opacity: 0; transform: translateY(24px); }
  to   { opacity: 1; transform: translateY(0); }
}

Understanding animation-range Intervals

The animation-range property defines which portion of a named interval drives the animation. Four intervals exist:

cover — from first contact to fully leaving the viewport (most common).

entry — the element entering the viewport.

exit — the element leaving the viewport.

contain — the phase where the element is fully inside the viewport (only when the element is smaller than the viewport).

Percentages are relative to the chosen interval, not the whole scroll. For example, entry 0% entry 60% means “from 0% to 60% of the entry phase.”

Staggered Entrances Without animation-delay

In scroll-driven animations, animation-delay delays timeline progress, not milliseconds, so using it for staggering breaks. The correct method offsets animation-range per element via :nth-child:

.list > :nth-child(2n) { animation-range: entry 5% entry 85%; }
.list > :nth-child(3n) { animation-range: entry 10% entry 90%; }

A newer syntax animation-delay: calc(sibling-index() * 40ms) is cleaner but has very narrow support as of writing; the nth-child approach with 4–6 bands remains the most reliable for production.

Compositor-Friendly Properties Only

Because the animation runs on the compositor, only compositor-friendly properties — transform and opacity — guarantee main-thread independence. Animating width, height, top, or margin forces layout every frame, negating the benefit:

/* ❌ Triggers layout each frame */
@keyframes bad { from { width: 0 } to { width: 100% } }

/* ✅ Runs entirely on compositor */
@keyframes good { from { transform: scaleX(0) } to { transform: scaleX(1) } }

Progressive Enhancement with @supports

Feature detection should be done in CSS with @supports, not user-agent sniffing. The base state provides a usable static appearance; the enhanced animation wraps inside a support query:

.progress { transform: scaleX(0); } /* default: visible without animation */

@supports (animation-timeline: scroll()) {
  .progress {
    animation: grow linear;
    animation-timeline: scroll(root);
  }
}

Browser support: Chrome 115+, Safari 26+; Firefox does not enable it by default. For full cross-browser coverage, fall back to IntersectionObserver for entrance animations and scroll + requestAnimationFrame for progress bars.

View Transitions: Letting Two Screens Morph Automatically

What It Does

document.startViewTransition(update)

performs three steps:

Capture a screenshot of the old state .

Execute the update callback (synchronously mutate the DOM).

Capture a screenshot of the new state and interpolate between matching elements by name.

document.startViewTransition(() => {
  list.classList.toggle('expanded');
});

The default is a full cross-fade. To make a specific element “fly” between pages, give it a view-transition-name in both the old and new states: .card { view-transition-name: hero; } The browser automatically computes the transform from the old position/size to the new one — the entire FLIP workflow (first/last/invert/play) is handled internally.

The Hard Constraint: Unique Names

view-transition-name

must be globally unique at any given moment. If ten list items all share hero, the transition fails. Assign stable unique names per item (e.g., card-${id}), and promote the clicked item to the shared hero name only during the transition:

items.forEach(item => {
  item.el.style.viewTransitionName = `card-${item.id}`; // unique per item
});

function openDetail(item) {
  item.el.style.viewTransitionName = 'hero'; // old state
  document.startViewTransition(() => {
    detailImage.style.viewTransitionName = 'hero'; // new state
    renderDetail(item);
  });
}

The hero name can exist on only one side (old or new) at a time; having it on both simultaneously causes a conflict.

Pseudo-Element Tree for Customization

The transition exposes a pseudo-element hierarchy:

::view-transition
└── ::view-transition-group(hero)        ← box motion (translate/scale)
    ├── ::view-transition-image-pair(hero)
    │   ├── ::view-transition-old(hero)  ← old screenshot
    │   └── ::view-transition-new(hero)  ← new screenshot
group

controls how the box moves; old and new control how the content cross-fades. To keep the content static while the box moves, disable the default cross-fade on old / new and adjust the group animation:

::view-transition-group(*) { animation-duration: 400ms; }

::view-transition-old(hero),
::view-transition-new(hero) {
  animation: none;
  mix-blend-mode: normal;
}

List Reordering: A Direct FLIP Replacement

Reordering a list becomes a one-liner: call startViewTransition and re-render the DOM. The only prerequisite is a stable unique name per item (e.g., item-${id}). The browser handles the rest.

function reorder(nextItems) {
  document.startViewTransition(() => {
    render(nextItems); // direct DOM reorder, no coordinate math
  });
}

SPA Router Integration: The Timing Pitfall

In a single-page application, the router guard must await the next microtask tick before resolving the transition callback; otherwise the “new state” screenshot captures the old DOM, producing a flash with no visible transition:

router.beforeEach((to, from, next) => {
  if (!document.startViewTransition) return next();

  document.startViewTransition(async () => {
    next();
    await nextTick(); // wait for DOM to actually update
  });
});

The callback can return a Promise; the new screenshot waits for it to resolve. Omitting await nextTick() is a subtle bug that is hard to diagnose from the symptom alone.

Multi-Page Applications Need Not Become SPAs

Traditional sites can enable cross-page transitions with two lines of CSS, provided navigation stays same-origin:

@view-transition {
  navigation: auto; /* enables transitions for same-origin navigations */
}

Give corresponding elements the same view-transition-name (e.g., .post-title on the list page and .detail-title on the detail page both named post-title). The title will animate smoothly across the navigation. Supported in Chrome 126+.

Accessibility Baseline: Not Optional

Transitions are purely decorative. Failing to honor prefers-reduced-motion is a non-compliant implementation. Disable all transition animations in that media query:

@media (prefers-reduced-motion: reduce) {
  ::view-transition-group(*),
  ::view-transition-old(*),
  ::view-transition-new(*) {
    animation: none !important;
  }
}

This requirement belongs on the same acceptance checklist as keyboard operability.

JavaScript-side feature detection follows the same progressive-enhancement pattern:

if (!document.startViewTransition) update();
else document.startViewTransition(() => update());

Combining Both APIs

An e-commerce product list can use scroll-driven entrance animations for cards and a View Transition for the clicked product image:

.product {
  animation: rise linear both;
  animation-timeline: view();
  animation-range: entry 0% entry 70%;
}
.product-img { view-transition-name: none; }
.product[data-active] .product-img { view-transition-name: hero; }
function openDetail(el, id) {
  el.dataset.active = ''; // assign name only to clicked item
  document.startViewTransition(() => {
    history.pushState({}, '', `/product/${id}`);
    renderDetail(id);
  }).finished.finally(() => {
    delete el.dataset.active; // cleanup after transition ends
  });
}

The transition.finished promise is the reliable way to run post-transition cleanup, avoiding fragile setTimeout guesses.

Quick Reference

Scroll progress bar: animation-timeline: scroll(root) + transform.

Element entrance on scroll: animation-timeline: view() + animation-range: entry 0% entry 60%.

Exit-only animation: animation-range: exit 0% exit 100%.

Staggered entrance: offset animation-range via :nth-child.

Legacy fallback: wrap enhanced CSS in @supports (animation-timeline: scroll()).

Continuous morph between states: document.startViewTransition(() => sync DOM update).

Opt an element into transition: view-transition-name: hero (must be globally unique).

Adjust transition timing: ::view-transition-group(hero) { animation-duration }.

List add/remove/reorder: unique name per item + direct DOM reorder.

MPA transitions: @view-transition { navigation: auto } (same-origin only).

Run code after transition: startViewTransition(...).finished.then().

Accessibility floor: prefers-reduced-motion media query with animation: none.

In summary: hand scroll-driven timelines to animation-timeline and state-to-state morphing to startViewTransition. Both run off the main thread, leaving it free for business logic.

The full version also covers cover / contain interval boundaries, the view() inset parameter, nested pseudo-element structures, and three SPA router timing patterns.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

accessibilityCSSView Transitions APIcompositor threadprogressive enhancementanimation-timelinescroll-driven animationsFLIP
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.