Sub topic 7
Building a shared-element transition
This chapter assumes you can call document.startViewTransition(), know the pseudo-element tree (::view-transition-group, -image-pair, -old, -new), and are comfortable with promises. A shared-element transition makes one element look like it travels from its place in the old view to its place in the new view. The standard example is a card thumbnail that grows into a detail-page hero image.
How the browser pairs elements
The browser does not know that a card image and a detail image are "the same thing". You tell it by giving an element in the old state and an element in the new state the same view-transition-name. The browser then:
- Captures the old state, including a snapshot of the element named
hero. - Runs your update callback.
- Captures the new state, including a snapshot of whichever element is now named
hero. - Builds one group for
hero, containing an old image and a new image. - Animates the group's position and size from the old box to the new box. It cross-fades the old and new images inside the group.
The rest of the page is still handled by the root group, which cross-fades as usual. The named element is lifted out of that snapshot and animates on its own.
The naming sequence
The timing of the name assignments is the part people most often get wrong. The name must be on the old element before the old snapshot is taken. It must be on the new element after the update runs, and it must not be on the old element at that point. This function does all three:
function openDetail(card, id) {
if (!document.startViewTransition) {
showDetail(id);
return;
}
card.style.viewTransitionName = 'hero';
const transition = document.startViewTransition(() => {
card.style.viewTransitionName = '';
showDetail(id);
document.querySelector('.detail-image').style.viewTransitionName = 'hero';
});
transition.finished.finally(() => {
const detailImage = document.querySelector('.detail-image');
if (detailImage) detailImage.style.viewTransitionName = '';
});
}Here is what each step does:
card.style.viewTransitionName = 'hero'runs synchronously beforestartViewTransition(). The old state is captured right after the call, so the card is already named.- Inside the callback, the card's name is cleared first. If the list stays in the DOM, two elements would otherwise carry
heroin the new state. - The detail image is named only after
showDetail()has created it. Naming it earlier is impossible, because it does not exist yet. - The
finishedhandler removes the name once the animation is over. A leftover name keeps the element in its own group and can cause problems the next time you navigate.
For this to run, showDetail has to put an element with class detail-image into the page. This version builds it with DOM methods and no HTML strings:
const items = [
{ id: '1', src: '/img/lighthouse.jpg', title: 'Lighthouse' },
{ id: '2', src: '/img/harbor.jpg', title: 'Harbor' }
];
function showDetail(id) {
const item = items.find((entry) => entry.id === id);
const view = document.querySelector('#content');
const img = document.createElement('img');
img.className = 'detail-image';
img.src = item.src;
img.alt = item.title;
view.replaceChildren(img);
}Going back works the same way with the roles reversed. Name the detail image before the transition, clear it in the callback, render the list, and name the matching card.
Tuning the motion
The group pseudo-element carries the position and size animation, so that is where you change how the element travels:
::view-transition-group(hero) {
animation-duration: 400ms;
animation-timing-function: ease-in-out;
}You are overriding the browser's default animation on the group. Do not replace it with your own @keyframes unless you also recreate the transform and size animation, because the default does that work for you.
When the two boxes differ in shape
A card thumbnail is often square and the detail image is wide. By default the old and new snapshots keep their own aspect ratios while the group changes size, so one of them can look stretched or leave gaps. A common fix is to make both snapshots fill the group and crop instead of distort:
::view-transition-old(hero),
::view-transition-new(hero) {
height: 100%;
object-fit: cover;
overflow: clip;
}This works because the snapshots behave like replaced elements, so object-fit applies to them. If the real images use object-fit: cover as well, the crop will match what the user sees before and after the transition.
What changes while the transition runs
A named element is treated differently from ordinary content, and these differences cause most surprises:
- Stacking. Named groups paint in an overlay above the whole page. Ordinary
z-indexrules no longer apply to them. To change the order of two named groups, setz-indexon their::view-transition-group()pseudo-elements. - Clipping. The group is not clipped by an ancestor's
overflow: hidden. An image that looked cropped inside a card may appear uncropped while it flies. Theoverflow: cliprule above is one way to restore the crop. - Containment. The element gets paint containment while it is named. Effects that rely on painting outside its box, such as a large
box-shadowor a child that overflows, can be cut off in the snapshot. - Live content. Snapshots are static images. Video, an animated GIF, or a CSS animation inside the element freezes at capture time and does not play during the transition.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| Image fades instead of moving | The name is missing from the old or the new element | Set the name before the call and again inside the callback |
| No animation at all | Two elements share the name in one state | Clear the old name inside the callback |
| Image jumps on the next navigation | A stale name was left on the detail image | Clear it in `finished` |
| Image looks squashed mid-flight | The aspect ratios differ | Use `height: 100%` and `object-fit: cover` on the old and new pseudo-elements |
| Element flickers above the header | The group paints above everything | Set `z-index` on the group |
Exercise
In openDetail, why does the callback set card.style.viewTransitionName to an empty string before it sets the name on the detail image?
Show answer
After the callback runs, the browser captures the new state. If the card still had the name hero, two elements would carry it in that state. Duplicate names make the browser skip the transition, so the DOM updates with no animation. Clearing the card's name first leaves exactly one element named hero in the new state.
Exercise
A shared-element transition works, but the flying image looks stretched while it grows from a square card to a wide hero. Which pseudo-elements do you style, and with which declarations?
Show answer
Style ::view-transition-old(hero) and ::view-transition-new(hero). Set height: 100% and object-fit: cover so both snapshots fill the group and are cropped instead of distorted. Adding overflow: clip keeps the crop inside the group's box.