Sub topic 2
Writing Your Own Page Animations
Assume you know CSS selectors, @keyframes, and basic multi-page navigation. Each URL returns a separate HTML document.
Writing your own page animations
A cross-document view transition captures the old page and the new page. The browser exposes these snapshots through pseudo-elements. You can animate them with ordinary CSS:
@view-transition {
navigation: auto;
}
@keyframes slide-out {
to {
opacity: 0;
transform: translateX(-40px);
}
}
@keyframes slide-in {
from {
opacity: 0;
transform: translateX(40px);
}
}
::view-transition-old(root) {
animation: 200ms ease-in both slide-out;
}
::view-transition-new(root) {
animation: 300ms ease-out both slide-in;
}The root snapshot represents the whole page. Put the @view-transition rule in the stylesheet used by both the page being left and the page being opened. Without that opt-in, the navigation uses no cross-document transition.
Morphing shared elements between pages
A shared element is an element that appears on both pages, such as a post thumbnail and its detail-page hero image. Give the corresponding elements the same view-transition-name:
/* On the list page and the detail page */
.post-image {
view-transition-name: post-image;
}The name must be unique among transition participants in each document. The browser then matches the old and new snapshots and animates the element between its positions and sizes. Leave unrelated content in the root transition.
If a page contains several cards, assign the name only to the clicked card. The pageswap and pagereveal events can set that name from the source or destination URL.
Respecting reduced-motion preferences
Some users request less motion. Keep navigation functional while removing animation:
@media (prefers-reduced-motion: reduce) {
::view-transition-group(*),
::view-transition-old(*),
::view-transition-new(*) {
animation: none !important;
}
}Support and graceful fallback
View transitions are progressive enhancement. In an unsupported browser, the links still perform normal full-page navigation. Avoid making application correctness depend on transition events or transition-only styles. Test the site with transitions disabled, and check that missing shared elements do not break the page.
Exercise
What happens if the destination page has no element named post-image?
Show answer
The named-element morph cannot occur, but the page can still use the root transition or load normally without transition support.