|$ curl https://forge-ai.dev/api/markdown?path=docs/css/view-transitions
$cat docs/view-transitions-api.md
updated Recently·18 min read·published
View Transitions API
◆CSS◆Animations◆Advanced
Introduction
The View Transitions API provides a way to animate transitions between different states of a page or between pages during navigation. It captures a snapshot of the old state, renders the new state behind it, then crossfades between them — with optional custom animations via CSS pseudo-elements.
Basic SPA Transition
Use document.startViewTransition() to wrap a DOM update. The browser automatically captures old and new states.
view-transition-spa.js
JavaScript
| 1 | function updateContent(newHTML) { |
| 2 | if (!document.startViewTransition) { |
| 3 | // Fallback for unsupported browsers |
| 4 | document.getElementById("content").innerHTML = newHTML; |
| 5 | return; |
| 6 | } |
| 7 | |
| 8 | document.startViewTransition(() => { |
| 9 | document.getElementById("content").innerHTML = newHTML; |
| 10 | }); |
| 11 | } |
Custom Animations
Style the transition using ::view-transition-old() and ::view-transition-new() pseudo-elements. Name elements with view-transition-name for per-element control.
view-transition-custom.css
CSS
| 1 | /* Default crossfade for entire page */ |
| 2 | ::view-transition-old(root) { |
| 3 | animation: fade-out 0.3s ease-out; |
| 4 | } |
| 5 | |
| 6 | ::view-transition-new(root) { |
| 7 | animation: fade-in 0.3s ease-in; |
| 8 | } |
| 9 | |
| 10 | /* Per-element custom transition */ |
| 11 | .card { |
| 12 | view-transition-name: card; |
| 13 | } |
| 14 | |
| 15 | ::view-transition-old(card) { |
| 16 | animation: slide-out 0.3s; |
| 17 | } |
| 18 | |
| 19 | ::view-transition-new(card) { |
| 20 | animation: slide-in 0.3s; |
| 21 | } |
| 22 | |
| 23 | @keyframes fade-out { |
| 24 | from { opacity: 1; } |
| 25 | to { opacity: 0; } |
| 26 | } |
| 27 | |
| 28 | @keyframes slide-in { |
| 29 | from { transform: translateX(100%); } |
| 30 | to { transform: translateX(0); } |
| 31 | } |
ℹ
info
Named elements must have unique view-transition-name values per page. The browser captures them as separate layers in the transition pseudo-element tree.