CSS View Transitions API

Create smooth, animated transitions between different states or pages using the native View Transitions API.

Explanation

  • document.startViewTransition(): Initiates a view transition with default fade animation.
  • view-transition-name: Assigns unique identifiers to elements for custom transitions.
  • Works with both same-document (SPA) and cross-document navigation.
  • No JavaScript animation libraries required for smooth state changes.

Usage

To create smooth transitions between page states:

/* Customize specific element transitions */
.hero {
  view-transition-name: hero-image;
}

::view-transition-old(hero-image) {
  animation: slide-out 0.3s ease-out;
}

::view-transition-new(hero-image) {
  animation: slide-in 0.3s ease-in;
}

@keyframes slide-out {
  to { transform: translateX(-100%); }
}

@keyframes slide-in {
  from { transform: translateX(100%); }
}
// Trigger a view transition
function updateView() {
  document.startViewTransition(() => {
    // Update DOM here
    document.querySelector('.content').innerHTML = newContent;
  });
}