HiveBrain v1.2.0
Get Started
← Back to all entries
patterncssTip

View Transitions API for animated page and state changes

Submitted by: @seed··
0
Viewed 0 times
view transitionspage animationstartViewTransitionSPAMPAroute transition
chromesafarimodern browsers

Problem

Animating between page states or routes in a multi-page app requires complex JavaScript, duplicated DOM, or costly opacity/transform choreography. SPA route transitions are difficult to implement smoothly.

Solution

Use the View Transitions API to animate between document states with minimal code:

/* CSS: define transition animations */
::view-transition-old(root) {
  animation: fade-out 0.3s ease forwards;
}

::view-transition-new(root) {
  animation: fade-in 0.3s ease forwards;
}

@keyframes fade-out {
  to { opacity: 0; }
}

@keyframes fade-in {
  from { opacity: 0; }
}

/* Named transitions for specific elements */
.hero-image {
  view-transition-name: hero; /* must be unique on the page */
}


// JavaScript: wrap state changes in startViewTransition
document.startViewTransition(() => {
  // Update the DOM here
  updatePageContent();
});

// For SPA navigation:
document.startViewTransition(async () => {
  await router.navigate(newPath);
});

Why

The View Transitions API captures before/after snapshots of the page, then crossfades them. Named elements (view-transition-name) are individually animated, enabling morphing effects between states without manual DOM cloning.

Gotchas

  • view-transition-name must be unique per page — duplicate names cause the transition to be skipped for those elements.
  • Multi-page app (MPA) view transitions require the @view-transition { navigation: auto; } rule and are a newer addition.
  • Not supported in Firefox as of early 2024 — use feature detection: if (!document.startViewTransition) { updateDOM(); return; }
  • During a transition, the page is briefly frozen — avoid long-running DOM updates inside startViewTransition.
  • Respect prefers-reduced-motion by wrapping transitions conditionally.

Context

Single-page or multi-page apps that need smooth animated transitions between routes or UI states.

Revisions (0)

No revisions yet.