Sub topic 6
Naming elements with view-transition-name
This chapter assumes you can call document.startViewTransition(), know that the browser captures an old and a new snapshot, and can select the ::view-transition-* pseudo-elements. Here you will learn how to give an element its own snapshot.
Why names matter
By default, the browser captures the whole page as one snapshot called root. Everything inside it cross-fades together. An element cannot move or resize on its own, because it is only pixels inside the root image.
The view-transition-name property changes this. An element with a name is pulled out of root and captured as a separate snapshot. The browser then builds a group for that name and animates it on its own.
Setting a name
Give the property any custom identifier except none. The value none is the default and means the element is not captured separately.
.site-header {
view-transition-name: site-header;
}When this page runs a view transition, the header gets its own pseudo-element subtree. You can style it with the name in parentheses:
::view-transition-group(site-header) {
animation-duration: 500ms;
}The name appears in ::view-transition-group(), ::view-transition-image-pair(), ::view-transition-old() and ::view-transition-new().
What the browser does with a name
At capture time, the browser looks for elements with a name in the old state. After your update callback runs, it looks again in the new state. It then pairs them by name:
- A name in both states gives one group. The browser animates position and size from old to new, and cross-fades the contents.
- A name only in the old state gives an old image that fades out.
- A name only in the new state gives a new image that fades in.
Rules to remember
- A name must be unique among rendered elements in a state. If two elements share a name, the transition is skipped and the promises reject.
- The name must be set before the old snapshot is taken, and again in the new state, if you want a pairing.
- Elements that are not rendered (for example
display: none) are not captured. - A named element creates a stacking context and a containing block, so it may paint differently from before. Check overlapping content and
overflowclipping.
Setting a name from JavaScript
This sets a name on the clicked card only, so there are no duplicates.
function highlight(card, id) {
card.style.viewTransitionName = `card-${id}`;
document.startViewTransition(() => {
card.classList.add('highlighted');
});
}Exercise
Two cards both have view-transition-name: card when you call startViewTransition(). What happens, and how do you fix it?
Show answer
The browser skips the transition because the name is not unique, and the update callback still runs. Fix it by giving each card a unique name, such as card-${id}, or by naming only the one card involved in the transition.