2 min read

CSS View Transitions API

The View Transitions API provides a mechanism for easily creating animated transitions between different DOM states. It can animate changes within a single-page application (SPA) or even between full page navigations (MPA).

1. The Concept

When a transition starts, the browser captures a screenshot of the old state and the new state. It then creates a pseudo-element tree overlaying the page, allowing you to animate between the "old" image and the "new" image using standard CSS animations.

2. Basic Usage (SPA)

To trigger a view transition in JavaScript, wrap your DOM update logic in document.startViewTransition().

function updateContent() {
  document.startViewTransition(() => {
    // Update the DOM here
    document.body.innerHTML = '<h1>New Content</h1>';
  });
}

The browser automatically handles a cross-fade between the old and new states.

3. Customizing Transitions

You can customize the animation using CSS pseudo-elements.

  • ::view-transition
  • ::view-transition-group(name)
  • ::view-transition-image-pair(name)
  • ::view-transition-old(name)
  • ::view-transition-new(name)

By default, everything is grouped under the root name.

::view-transition-old(root),
::view-transition-new(root) {
  animation-duration: 0.5s;
}

4. Naming Elements (view-transition-name)

To animate specific elements independently (e.g., a header staying in place while the content fades, or an image moving from a list to a detail view), you must give them a unique view-transition-name.

.header {
  view-transition-name: main-header;
}

.hero-image {
  view-transition-name: hero-img;
}

Important: view-transition-name must be unique on the page at the time of the transition.

5. Multi-Page Applications (MPA)

The API also supports transitions between full page reloads. To enable this, you need to add a meta tag or CSS rule.

CSS:

@view-transition {
  navigation: auto;
}

When the user navigates from page-a.html to page-b.html, if both pages opt-in, the browser will perform a view transition.

6. Browser Support

  • Chrome/Edge: Supported.
  • Safari: In development.
  • Firefox: In development.

programming/css/css programming/css/transitions-and-animations programming/css/pseudo-classes-and-pseudo-elements programming/javascript/vanilla/javascript