Skip to content

Lesson 25 of 52Modern CSS

View Transitions and Scroll-Driven Animations

Animate between page states with the View Transition API, link whole pages with cross-document transitions, and tie animation to scroll with pure CSS.

16 min read0/4 questions

A designer hands you a prototype: when you sort a product grid the cards glide to their new places, when you open a product the thumbnail grows into the hero image on the next page, and a thin bar along the top fills as you read. Two years ago each of those meant a JavaScript animation library, measuring element positions before and after every change, and a scroll listener firing hundreds of times a second. Today the browser does all three. The View Transition API animates between two DOM states (even across full page loads), and scroll-driven animations bind ordinary CSS keyframes to scroll position, off the main thread. This lesson covers both in plain HTML, CSS and a few lines of JavaScript; Animation and View Transitions in the React course shows the same browser feature through React's component.

The problem view transitions solve

Animating a change of state is easy when you know both states up front: a transition from one class to another. It is hard when the DOM itself changes. Sorting a list re-orders elements, filtering removes some, navigating replaces the whole page. To animate those by hand you have to record where every element was, apply the change, measure where everything is now, then animate each element from old to new with transforms. That technique is called FLIP (First, Last, Invert, Play), and it is fiddly, slow on large lists and impossible across a page load.

A view transition flips the approach around. The browser takes a picture of the old state, lets you change the DOM however you like, takes a picture of the new state, and animates between the two pictures in an overlay. Your real DOM is never animated, so it does not matter how you changed it.

Same-document transitions: startViewTransition

The whole API is one call. Wrap your DOM update in document.startViewTransition():

function update() {
  list.replaceChildren(...sorted);
}
 
if (!document.startViewTransition) {
  update();                     // older browser: just do it
} else {
  document.startViewTransition(update);
}

Same-document view transitions work in Chrome, Edge and Safari, and became Baseline when Firefox 144 shipped them in October 2025. The fallback above still matters for older browsers and costs one line: the update happens, only the animation is missing. That is the first principle of this whole lesson. Motion is an enhancement; the change must work without it.

What happens during that call, step by step:

document.startViewTransition(update)
Your codeBrowserOverlaystartViewTransition(update)capture oldcall update()capture new, build pseudo treeanimatefinished

You hand over the function that changes the DOM. Nothing has changed yet.

1/6

The object returned by startViewTransition has three promises, updateCallbackDone, ready and finished, plus skipTransition() to jump to the end. Two failure modes are worth memorising because they confuse people in code review:

  • Duplicate names. Every view-transition-name must be unique among rendered elements when a snapshot is taken. If two elements share a name, the transition is skipped (ready rejects with an InvalidStateError), although your update still runs. The page changes with no animation and an error in the console.
  • Slow updates. Rendering is frozen while your update runs. If it takes too long (a slow network request inside the callback), the browser gives up after a few seconds with a TimeoutError. Fetch first, then start the transition with an update that only touches the DOM.

Naming elements: view-transition-name and match-element

Without names, the whole page cross-fades as one image called root. To make individual elements glide, give them a view-transition-name. An element with the same name in the old and new state becomes one group that moves from its old box to its new one. A name only in the new state is an entry; only in the old state, an exit.

Naming twenty cards by hand (card-1, card-2...) used to require inline styles or generated CSS. Two newer values fix that, both supported in all current major browsers:

  • view-transition-name: match-element names an element by its identity: the same DOM node before and after is matched automatically. Perfect for re-ordering existing elements. It only works within one document, because a new page has new nodes.
  • view-transition-class puts a class on the generated pseudo-elements so you can style many groups with one selector: ::view-transition-group(.card).
HTML & CSS
<style> .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(110px, 1fr)); gap: 10px; list-style: none; padding: 0; } .card { view-transition-name: match-element; view-transition-class: card; padding: 12px; border-radius: 10px; color: white; font-weight: 600; } .card small { display: block; font-weight: 400; opacity: 0.85; } ::view-transition-group(.card) { animation-duration: 350ms; animation-timing-function: cubic-bezier(0.2, 0.8, 0.2, 1); } @media (prefers-reduced-motion: reduce) { ::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*) { animation: none !important; } } .bar { display: flex; gap: 8px; margin-bottom: 12px; flex-wrap: wrap; } button { font: inherit; padding: 6px 12px; }</style><div class="bar"> <button data-sort="price">Sort by price</button> <button data-sort="name">Sort by name</button> <button id="toggle">Hide sold out</button></div><ul class="grid" id="grid"></ul><p id="support"></p><script> const items = [ { name: "Kettle", price: 39, colour: "#0f766e", soldOut: false }, { name: "Toaster", price: 54, colour: "#7c3aed", soldOut: true }, { name: "Blender", price: 89, colour: "#b45309", soldOut: false }, { name: "Grinder", price: 25, colour: "#be123c", soldOut: false }, { name: "Scales", price: 18, colour: "#1d4ed8", soldOut: true }, { name: "Mixer", price: 120, colour: "#15803d", soldOut: false }, ]; const grid = document.getElementById("grid"); const els = new Map(items.map((item) => { const li = document.createElement("li"); li.className = "card"; li.style.background = item.colour; li.innerHTML = item.name + "<small>" + item.price + " GBP" + (item.soldOut ? ", sold out" : "") + "</small>"; return [item, li]; })); let order = items.slice(); let hideSoldOut = false; function render() { grid.replaceChildren(...order.filter((i) => !(hideSoldOut && i.soldOut)).map((i) => els.get(i))); } function withTransition(update) { if (!document.startViewTransition) return update(); document.startViewTransition(update); } document.querySelectorAll("[data-sort]").forEach((btn) => btn.addEventListener("click", () => { const key = btn.dataset.sort; withTransition(() => { order.sort((a, b) => (key === "price" ? a.price - b.price : a.name.localeCompare(b.name))); render(); }); })); document.getElementById("toggle").addEventListener("click", (event) => { withTransition(() => { hideSoldOut = !hideSoldOut; event.target.textContent = hideSoldOut ? "Show sold out" : "Hide sold out"; render(); }); }); render(); document.getElementById("support").textContent = document.startViewTransition ? "View transitions supported: the cards animate." : "No view transition support here: the update still works, without motion.";</script>

Preview

Sort and filter a few times. The JavaScript does nothing clever: it re-orders the real elements and replaces the children. The motion comes entirely from the snapshot and the match-element names. Change 350ms to 1200ms to watch the groups slide and resize slowly, then delete the view-transition-name line to see the plain whole-page cross-fade you get without names.

Predict the outputHTML

A transition runs on this page. How many ::view-transition-group pseudo-elements are created? Type a number.

<style>
.card { view-transition-name: match-element; }
.sidebar { view-transition-name: sidebar; }
.footer { view-transition-name: none; }
</style>
<aside class="sidebar">...</aside>
<div class="card">A</div>
<div class="card">B</div>
<div class="card">C</div>
<footer class="footer">...</footer>
Need a nudge? Hints walk you through it.

Customising the animation

The pseudo-element tree is ordinary CSS. Animation and View Transitions in the React course walks through it in detail; the short version is that every named group has a ::view-transition-group(name) that moves and resizes, holding ::view-transition-old(name) and ::view-transition-new(name) images that fade. Target them like any element:

/* slow down everything */
::view-transition-group(*) { animation-duration: 250ms; }
 
/* the header should not move or fade at all */
.site-header { view-transition-name: header; }
::view-transition-group(header) { animation: none; }
 
/* a new item scales in, a removed one scales out */
::view-transition-new(.card):only-child { animation: pop-in 200ms ease-out; }
::view-transition-old(.card):only-child { animation: pop-out 150ms ease-in; }

The :only-child trick works because an entry has only a new image in its pair and an exit has only an old one.

Direction with transition types

Going "next" and "back" should usually move in opposite directions. Types label a transition so CSS can choose animations: pass them when you start it, and match them with :active-view-transition-type().

HTML & CSS
<style> .slide { view-transition-name: slide; padding: 40px; font-size: 28px; font-weight: 700; color: white; border-radius: 12px; text-align: center; } @keyframes out-left { to { translate: -100% 0; opacity: 0; } } @keyframes in-right { from { translate: 100% 0; opacity: 0; } } @keyframes out-right { to { translate: 100% 0; opacity: 0; } } @keyframes in-left { from { translate: -100% 0; opacity: 0; } } html:active-view-transition-type(forward) { &::view-transition-old(slide) { animation: out-left 300ms ease-in both; } &::view-transition-new(slide) { animation: in-right 300ms ease-out both; } } html:active-view-transition-type(backward) { &::view-transition-old(slide) { animation: out-right 300ms ease-in both; } &::view-transition-new(slide) { animation: in-left 300ms ease-out both; } } .nav { display: flex; justify-content: space-between; margin-top: 12px; } button { font: inherit; padding: 6px 12px; }</style><div class="slide" id="slide"></div><div class="nav"><button id="prev">Back</button><button id="next">Next</button></div><script> const steps = [["Account", "#1d4ed8"], ["Address", "#7c3aed"], ["Payment", "#0f766e"], ["Done", "#15803d"]]; let i = 0; const slide = document.getElementById("slide"); function show() { slide.textContent = (i + 1) + ". " + steps[i][0]; slide.style.background = steps[i][1]; } function go(delta) { const next = Math.min(steps.length - 1, Math.max(0, i + delta)); if (next === i) return; const update = () => { i = next; show(); }; if (!document.startViewTransition) return update(); try { document.startViewTransition({ update, types: [delta > 0 ? "forward" : "backward"] }); } catch { document.startViewTransition(update); } } document.getElementById("next").addEventListener("click", () => go(1)); document.getElementById("prev").addEventListener("click", () => go(-1)); show();</script>

Preview

The object form startViewTransition({ update, types }) arrived after the function form, so the try falls back to an untyped transition in browsers that only know the original call. Type names are yours to choose; "forward" and "backward" are just a convention.

Cross-document transitions for multi-page sites

Everything so far needed JavaScript to change the DOM. A traditional multi-page site, where every link loads a new HTML document, can animate between pages with CSS only. Opt in on both the old and the new page:

styles.css
@view-transition {
  navigation: auto;
}
 
/* on the listing page and on the product page */
.product-photo { view-transition-name: var(--photo-name); }

Now a same-origin navigation (a link click, or back and forward) cross-fades the pages, and an element with the same view-transition-name on both pages morphs from its old position to its new one: the thumbnail grows into the hero image. Because each product needs a unique name, set it per element, for example style="--photo-name: photo-42" on the listing card and the same on the product page.

The rules:

  • Both documents must opt in, and they must be same-origin with no cross-origin redirect in between.
  • Only navigations the user starts on the page count. Typing a URL in the address bar does not animate.
  • The old page fires pageswap and the new page fires pagereveal, each with the ViewTransition object, so you can add types or names based on where the user is going.
  • If the new page is slow to render, the browser may snapshot it before your hero image exists. <link rel="expect" href="#hero" blocking="render"> tells the browser to wait until that element has been parsed.

Support is narrower than same-document transitions: Chrome, Edge and Safari (18.2 and later) support it, while Firefox does not yet, as of late 2026. In a browser without it the @view-transition rule is ignored and links navigate exactly as before, which is why you can ship it today. Check current support before promising it to a designer as part of a design.

Quick check
You add @view-transition { navigation: auto; } to the product page only. A user clicks from the listing page to a product page. What happens?
Need a nudge? A hint rules out a wrong answer.

Scroll-driven animations

The second half of this lesson is a different feature with a similar spirit. Normally a CSS animation runs on the document timeline: time passing. A scroll-driven animation runs on a scroll timeline instead, so 0 percent of the keyframes means "scrolled to the start" and 100 percent means "scrolled to the end". There is no duration; scroll position is the clock.

Two timeline functions cover nearly every case:

  • animation-timeline: scroll() tracks how far a scroll container has scrolled. scroll(root) uses the page, scroll(nearest) (the default) the nearest scrolling ancestor, scroll(self) the element itself, and you can add an axis such as scroll(root inline).
  • animation-timeline: view() tracks an element's own journey through its scroll container's visible area (its scrollport): from first peeking in at the bottom to leaving at the top.

animation-range chooses which slice of that journey the keyframes cover, with named ranges:

view() ranges for an element scrolling up the screen
  1. entry 0%

    Top edge appears

    The element's top edge reaches the bottom of the scrollport. Nothing is visible yet.

  2. entry 100%

    Fully in view

    The bottom edge has come in too. The entry range is the part where it is sliding in. A reveal usually ends here or a little later.

  3. contain

    Fully visible

    The whole element is inside the scrollport. For an element taller than the viewport, this is when it fills it.

  4. exit 0%

    Starts leaving

    The top edge reaches the top of the scrollport and begins to disappear.

  5. exit 100%

    Gone

    The bottom edge has left. The cover range spans the whole journey, from entry 0% to exit 100%.

HTML & CSS
<style> body { margin: 0; } .progress { position: fixed; inset: 0 0 auto 0; height: 5px; background: #2563eb; transform-origin: 0 50%; } @keyframes grow { from { transform: scaleX(0); } to { transform: scaleX(1); } } @keyframes reveal { from { opacity: 0; translate: 0 40px; } to { opacity: 1; translate: 0 0; } } @media (prefers-reduced-motion: no-preference) { @supports (animation-timeline: scroll()) { .progress { animation: grow linear both; animation-timeline: scroll(root); } .reveal { animation: reveal ease-out both; animation-timeline: view(); animation-range: entry 0% entry 100%; } } } @supports not (animation-timeline: scroll()) { .progress { display: none; } } article { max-width: 520px; margin: 0 auto; padding: 24px 16px 200px; } .reveal { padding: 16px; margin: 40px 0; border-radius: 10px; background: #f1f5f9; } .note { font-size: 13px; color: #475569; }</style><div class="progress"></div><article> <h1>Scroll me</h1> <p class="note" id="note"></p> <p>The blue bar at the top fills as you scroll, and each box below fades up as it enters. There is no script driving either effect.</p> <div class="reveal">1. Measure before you optimise.</div> <div class="reveal">2. Ship the smallest useful change.</div> <div class="reveal">3. Write the test that would have caught it.</div> <div class="reveal">4. Leave the code better than you found it.</div> <div class="reveal">5. Ask for review early.</div> <div class="reveal">6. Document the decision, not just the code.</div></article><script> document.getElementById("note").textContent = CSS.supports("animation-timeline: scroll()") ? "Scroll-driven animations are supported in this browser." : "Not supported here: the boxes are simply visible and the bar is hidden.";</script>

Preview

Scroll the preview. Change the reveal's range to entry 0% cover 50% so boxes finish fading in only when they reach the middle of the preview, or swap translate: 0 40px for scale: 0.9. Notice the order of declarations: animation-timeline comes after the animation shorthand. The shorthand resets animation-timeline to auto, so writing them the other way round silently turns your scroll animation back into a time-based one with no duration.

Support and the fallback rule

Scroll-driven animations work in Chrome and Edge (since 2023) and Safari 26. Firefox has implemented them but, as of late 2026, has not yet shipped them in a stable release, so they are not Baseline. Check webstatus.dev or caniuse before you rely on them.

That makes the structure of the demo the important part:

  1. The base styles show the content fully visible. The reveal keyframes start at opacity: 0, but they only apply inside the @supports and reduced-motion blocks, so in Firefox, or with reduced motion on, every box is simply there.
  2. @supports (animation-timeline: scroll()) gates the scroll animation itself.
  3. @media (prefers-reduced-motion: no-preference) means motion is opt-in for people who have not asked for less.

The classic bug is the reverse: .reveal { opacity: 0 } in the base styles and a scroll animation to fade it in. In any browser without support, or for a user with reduced motion, the content is invisible. A screen reader still reads it, so nobody notices in testing, and sighted users see blank space.

Quick check
Why is the order of these two declarations a bug? animation-timeline: view(); animation: reveal linear both;
Need a nudge? A hint rules out a wrong answer.

Performance: why this beats scroll listeners

The old way to build a reading progress bar was a scroll event listener that reads scrollY and writes a width. That code runs on the main thread, the same thread that runs your JavaScript, layout and React renders. When the main thread is busy, the bar stutters, and writing width forces layout on every scroll event.

A scroll-driven animation of transform or opacity can run on the compositor, the part of the browser that moves already-painted layers. It stays smooth even while the main thread is blocked. The same rule from Transitions and Animations applies with extra force: animate only transform (or the individual translate, scale and rotate properties) and opacity. Animating width, top or background-position on scroll forces layout or paint on every frame and drops you back to the main thread.

IntersectionObserver is still the right tool when you need JavaScript to run as something enters view: lazy-loading data, analytics impressions, starting a video. Its callbacks fire asynchronously, only when a threshold is crossed, so it is cheap. For a visual effect that follows scroll continuously, the CSS timeline wins. For a one-off reveal in browsers without scroll timelines, IntersectionObserver adding a class is a fine fallback.

View transitions have their own costs. Every named element is captured as an image, so naming hundreds of elements on a long page uses real memory and time. Name what moves meaningfully, keep durations around 150 to 350 milliseconds, and remember the page underneath is covered by the overlay until the animation ends, so a long transition makes the UI feel slower, not smoother.

Match the pairs0/5 matched

Match each effect to the best tool.

Choose an item, then its match on the other side.
Key terms
view transition
A browser-managed animation between two DOM states, done by snapshotting the old and new states and animating the snapshots.
view-transition-name
A CSS property that captures an element as its own group so it animates separately from the page; names must be unique.
match-element
A view-transition-name value that names elements by identity, so the same DOM node is matched before and after without writing names.
cross-document view transition
A transition between two same-origin pages, enabled in CSS on both with @view-transition { navigation: auto; }.
scroll timeline
A timeline whose progress is the scroll position of a container, used with animation-timeline: scroll().
view timeline
A timeline tracking an element's progress through its scroll container's visible area, used with animation-timeline: view().
animation-range
Chooses which part of a timeline, such as entry, exit or cover, the keyframes are mapped onto.