Motion in components
Learn web component animation: transitions on :host and inside, @keyframes in shadow DOM, prefers-reduced-motion, custom states, and view transitions.
- 01Put motion in the right placeDeclare
@keyframesand transitions inside the shadow root, and know that a transition on:hostmoves only the host and what inherits from it. - 02Respect reduced motionSwap big movement for a gentle fade with
prefers-reduced-motion, in CSS and in JavaScript, and give a kit one switch for it. - 03Animate states, parts, and viewsStart motion from a custom state, let the page style a part, find animations with
getAnimations(), and run view transitions next to shadow roots.
How do you animate a web component?
Leaf and Kettle's tea card has a Brew button. Meena wants a little steam to rise over the card while the tea brews. Ravi builds the shop's tea kit, and the card's styles live in its shadow root. Will keyframes work in there? And Kiran, one of the shop's regulars, has turned on Reduce motion on his phone. Moving things make him dizzy. What should the card do for him?
Put a component's motion inside its shadow root: its @keyframes, its transitions, and the custom state that starts them, like :state(brewing). A transition on :host animates only the host and what inherits from it. Add a @media (prefers-reduced-motion: reduce) rule that swaps big movement for a gentle fade.
Here is a small card that does all of it:
<tea-card>Green tea</tea-card> <script type="module"> import "./tea-card.js"; const card = document.querySelector("tea-card"); const steam = card.shadowRoot.querySelector(".steam"); card.addEventListener("click", () => { const names = steam.getAnimations().map((animation) => animation.animationName); console.log("Steam:", names.join() || "still"); });</script>- In the
tea-card.jstab, lines 3 to 7 declare keyframes namedsteam-rise: the values an animation passes through. The steam starts see-through, shows at the halfway point, and fades out 16px higher.translatemoves an element without moving anything around it. - Line 8 declares a second set,
steam-fade: the same fade, with no movement. - Line 9 draws the steam: a small gray bar, see-through at rest.
- Line 10 runs
steam-riseon the steam while the card is in thebrewingstate. Each rise takes 600ms, andinfiniterepeats it. - Lines 11 to 13 swap in
steam-fadewhen the person asks for reduced motion. - Lines 23 to 27 turn the
brewingstate on and off when Brew is pressed. A custom state is a name a component turns on and off from inside. Lesson 12.3 built them. - On the page, line 6 finds the steam. Lines 7 to 10 print its animations on every click on the card.
Press Brew. The steam rises, and it prints Steam: steam-rise. Press Brew again. The state goes away, the steam stops, and it prints Steam: still. getAnimations() lists the animations running on an element right now. It brings the styles up to date first, so it already sees the animation the click just started.
A music box carries its tune inside, pinned on a little drum. Take it to a friend's house and wind the key. The same tune plays, and the little dancer turns. Nothing in the room has to know the tune.
- In real life: The tune pinned on the box's drum
- In CSS:
@keyframes steam-rise, inside the shadow root - In real life: Winding the key
- In CSS: Turning on
:state(brewing) - In real life: The little dancer that turns
- In CSS: The
.steamelement - In real life: Taking the box to a friend's house
- In CSS: Using the card on another page
A component carries its own motion. Its keyframes, its transitions, and its reduced-motion version live in its shadow root. A custom state starts the motion, and the page sees that state from outside.
If you've animated a page before, these are the same tools. Web performance lesson Compositor-friendly animation covers which properties are cheap to animate, and Animation with JavaScript covers timing. This lesson is about what changes when the element sits in a shadow root.
Does a transition on :host animate the whole component?
A transition makes a change gradual. Instead of jumping from one value to the next, the browser moves between them over a time you choose, like 300ms. You declare it with the transition property, on the element whose value changes.
Lesson 11.2 styled the host, the custom element itself, with :host from inside the shadow root. So does a transition on :host animate the whole card? Move the transition between the host and the steam, and press Brew:
<tea-card>Green tea</tea-card> <script type="module"> import "./tea-card.js"; const card = document.querySelector("tea-card"); const [steam, name] = card.shadowRoot.querySelectorAll(".steam, h3"); const moving = (element) => element.getAnimations().map((animation) => animation.transitionProperty).join(", ") || "nothing"; card.addEventListener("click", () => { console.log("Host:", moving(card)); console.log("Name:", moving(name), "Same color as the host?", getComputedStyle(name).color === getComputedStyle(card).color); console.log("Steam:", moving(steam)); });</script>Press Brew. It prints Host: background-color, color, then Name: nothing Same color as the host? true, then Steam: nothing. The host's background and text color change smoothly. The name has no transition of its own, but it takes the host's color at every step. The steam's opacity isn't the host's, so it jumps from 0 to 1.
- In the
tea-card.jstab, line 3 is the host's look at rest: a white background and black text. Line 4 turns them linen and sienna while the card brews. - Line 5 draws the steam, see-through. Line 6 shows it while the card brews.
- Line 7 is the only line that changes: where the transition is declared.
- On the page, line 6 finds the steam and the name. Line 7 makes
moving(), which lists the property each running transition animates, ornothing. Lines 9 to 11 print the host, the name, and the steam.
With the transition on :host, it prints Host: background-color, color, then Name: nothing Same color as the host? true, then Steam: nothing. The background and the text fade from one color to the other, but the steam pops in at once. With the transition on .steam, the steam fades in, and the host's colors jump.
Why does the name follow the host?
The name has no transition of its own, yet its color changes smoothly. That's because color is inherited: an element with no color of its own takes its parent's. While the host's color moves from black to sienna, the name takes each step's color. Chrome shows it: with the transition paused halfway, the host and the name are both rgb(80, 41, 23).
In Leaf and Kettle's back room, Ravi slides the ceiling light's dimmer. The whole room glows brighter, step by step. But the desk lamp has its own switch. When he turns it on, it's on at once. To fade it in, the lamp needs a dimmer of its own.
- In real life: The dimmer on the ceiling light
- In CSS: A transition on
:host - In real life: Everything lit by the ceiling light
- In CSS: Inherited values inside, like the name's
color - In real life: The desk lamp with its own switch
- In CSS: An inner element with its own value, like the steam's
opacity - In real life: Fitting the lamp with a dimmer of its own
- In CSS: A transition rule on
.steam, inside the shadow root
Why doesn't the host's transition reach the steam?
The transition property itself isn't inherited. MDN lists it as not inherited, and Chrome agrees: the steam's transition-duration stays 0s, whatever the host says. So every inner element that changes a value of its own, like the steam's opacity, needs its own transition rule inside the shadow root. Why it matters: when part of a component jumps instead of fading, look for the element whose own value changed.
Two more things about the host:
- A host's
opacityfades the whole card, inside and all. MDN says it applies to the element as a whole, contents included. The inner elements keep their own values: halfway through, the host'sopacityis0.5, and the steam's own is still1. - The page can still change the host's transition. A page rule like
tea-card { transition: none; }beats:host, as lesson 11.4 showed. Then the host's colors jump.
Where do @keyframes go in a web component?
A transition runs between two values. For more steps, like the steam's rise and fade, you write keyframes: an @keyframes rule with a name and the values at each point. The animation property then runs them by name.
Lesson 11.7 found that an @font-face rule inside a shadow root is ignored. Keyframes are different: the overview's card declared steam-rise inside its shadow root, and it ran. Where else can a card get keyframes? Try three choices:
<style> @keyframes puff { from, to { opacity: 0; } 50% { opacity: 1; } }</style><tea-card>Green tea</tea-card> <script type="module"> import "./tea-card.js"; const card = document.querySelector("tea-card"); const steam = card.shadowRoot.querySelector(".steam"); const names = (element) => element.getAnimations().map((animation) => animation.animationName).join() || "nothing"; card.addEventListener("click", () => console.log("Steam:", names(steam), "Host:", names(card)));</script>Press Brew. In Chrome it prints Steam: steam-puff Host: nothing. Line 5 names steam-puff, which line 3 declares in the same shadow root. The steam puffs while the card brews.
- On the page, line 2 declares the page's own keyframes,
puff: a fade in and out. - In the
tea-card.jstab, line 3 declares the card's keyframes,steam-puff: the same fade. Line 5 is the only line that changes. It names one of the two, on the steam or on the host. - On the page, line 10 makes
names(), which lists the names of an element's running animations. Line 11 prints the steam's and the host's on every click.
Press Brew with each choice. The card's own keyframes print Steam: steam-puff Host: nothing. The page's keyframes print Steam: nothing Host: nothing in Chrome: no animation starts at all. And the card's keyframes on :host print Steam: nothing Host: steam-puff. So keyframes inside a shadow root work for the elements inside, and for the host too.
Why can't the card use the page's keyframes?
Recall lesson 11.7's term. A keyframes name is a tree-scoped name: it belongs to the tree whose stylesheet declares it, the page or one shadow root. CSS Shadow says a name used inside a shadow root should look in its own tree first, and then in the trees around it. So by the spec, puff should work inside the card.
Browsers have taken a long time to agree. In 2024, Chrome's article on CSS names found no browser doing it. Adobe's tracker rates @keyframes across shadow roots as "use with caution". The course ran the same pages in Chrome, Firefox, and WebKit, Safari's engine. Read each row across:
| Who | @keyframes inside the shadow root | @keyframes in the page |
|---|---|---|
| The CSS Shadow spec | They work inside, on :host too. The page and its ::part() rules can't use them. | Every shadow root below can use them. |
| Chrome and Edge | They work inside, on :host too. The page and its ::part() rules can't use them. | Only the page's own rules can use them, ::part() rules included. Names inside a shadow root don't find them. |
| Firefox | They work inside, on :host too. The page can use them too, through ::part() or a rule on the tag. | Every shadow root below can use them. |
| Safari | They work inside, on :host too. The page and its ::part() rules can't use them. | Every shadow root below can use them. |
One thing holds in every row: keyframes declared inside the shadow root work inside it, and on :host. Why it matters: declare a component's keyframes in its own sheet, and they work in every browser.
How do you respect prefers-reduced-motion in a web component?
Kiran turned on Reduce motion in his phone's accessibility settings. The browser passes that wish to CSS as the prefers-reduced-motion media feature. It has two values: no-preference, and reduce when the person asked for less motion.
Why do people ask? Moving things can make some people dizzy or sick. MDN names vestibular motion disorders: problems with the inner ear's sense of balance. Scaling or panning large things can set them off.
WCAG, the web's accessibility guidelines, has a rule for this. Success Criterion 2.3.3, Animation from Interactions, is at level AAA. Motion that an interaction starts should be possible to turn off, unless the motion is essential. And its definition of motion leaves out changes of color or opacity that don't change an element's size, shape, or position.
So reduced motion means less motion, not no feedback. MDN's own example tones a pulsing box down to a gentle fade. Chrome's motion guidance says the same: keep color changes, and take out the movement, scaling, and spinning. The overview's card did that in four lines, lines 10 to 13 of its tab:
:host(:state(brewing)) .steam { animation: steam-rise 600ms ease-out infinite; }
@media (prefers-reduced-motion: reduce) {
:host(:state(brewing)) .steam { animation-name: steam-fade; }
}- Line 1 runs
steam-risewhile the card brews. - Line 2 is a media query: the rules inside it apply only when the person asks for less motion.
- Line 3 swaps the animation's name for
steam-fade. The timing stays the same. Only the movement goes.
The query works inside a shadow root like any other rule. Try it in Chrome with DevTools' emulation. Open the Rendering tab. Under "Emulate CSS media feature prefers-reduced-motion", pick prefers-reduced-motion: reduce. Then press Brew in the overview. It prints Steam: steam-fade, and the steam fades in place.
At Leaf and Kettle, the kettle's steam and hiss are part of the show. One customer finds the hiss too much and asks for a quiet table. So when his tea is ready, the shop turns on a small ready light by his table. He still knows his tea is ready. He just isn't startled.
- In real life: The steam and the hiss of the kettle
- In CSS: The full animation,
steam-rise - In real life: A customer who asks for a quiet table
- In CSS:
prefers-reduced-motion: reduce - In real life: The small ready light by their table
- In CSS: The gentle version,
steam-fade - In real life: Not telling them at all
- In CSS: Turning every animation off
Checking from JavaScript
CSS rules follow the media query by themselves. A script doesn't. matchMedia() takes the same query and tells your code whether it matches:
const reduce = matchMedia("(prefers-reduced-motion: reduce)");
console.log("Reduce motion?", reduce.matches);Line 1 asks the question. Line 2 prints Reduce motion? false, or Reduce motion? true on a device that asks for less motion. Nathan Smith's CTA modal component checks the same query in its CSS and in its JavaScript, for this reason.
One switch for a whole kit
A kit with many components could repeat the media query in each one. There's a shorter way. Lesson 12.1 showed that custom properties cross the shadow boundary. So the kit can keep one number, --tea-motion: 1 for full motion, and 0 for none. Each component multiplies its movement by it. And lesson 12.6's base sheet, which every component adopts first, can set it to 0 when the person asks:
<style>:root { --tea-motion: 1; }</style><label><input type="checkbox"> Less motion</label><tea-card>Green tea</tea-card> <script type="module"> import "./tea-card.js"; const card = document.querySelector("tea-card"); const steam = card.shadowRoot.querySelector(".steam"); document.querySelector("input").addEventListener("change", (event) => { document.documentElement.style.setProperty("--tea-motion", event.target.checked ? "0" : "1"); }); card.addEventListener("click", () => { console.log("Motion:", getComputedStyle(steam).getPropertyValue("--tea-motion")); });</script>- In the
base.jstab, lines 3 to 5 apply only under reduced motion. Then every host that adopts the sheet gets--tea-motion: 0. - In the
tea-card.jstab, line 8 rises 16px times--tea-motion. The1after the comma is the value when nothing sets it. Line 20 adopts the base sheet first. - On the page, line 1 sets the token to 1. Line 2 is a Less motion checkbox. Lines 9 to 11 set the token on
:rootwhen the box changes. Lines 12 to 14 print the value the steam gets.
Press Brew. It prints Motion: 1, and the steam rises. Press Brew to stop, tick Less motion, and press Brew again. It prints Motion: 0, and the steam fades in place, because 16px times 0 is 0. With reduced motion emulated in DevTools, it prints Motion: 0 even with the box unticked.
Why it matters: one rule in the base sheet covers every component, and the page can offer a Less motion switch of its own. WCAG's examples include a site-wide setting like that, which turns off motion the page doesn't need. For view transitions, web performance lesson View transitions and performance shows that skipping the transition under reduced motion is faster than turning its animations off.
How do you animate custom states and parts?
A custom state is a name that a component turns on and off from inside, and CSS reads it with :state(), as lesson 12.3 showed. That makes a state a good switch for motion. Inside the card, :host(:state(brewing)) started the steam. From the page, tea-card:state(brewing) does the same for the page's rules.
Lesson 12.2 named inner elements as parts, so the page can style them with ::part(). Put the two together, and the page can animate a part while the card brews:
<style> @keyframes blush { 50% { color: sienna; } } tea-card::part(steam) { background: slategray; } tea-card:state(brewing)::part(name) { animation: blush 1s infinite; }</style><tea-card>Green tea</tea-card> <script type="module"> import "./tea-card.js"; const card = document.querySelector("tea-card"); const [steam, name] = card.shadowRoot.querySelectorAll("[part]"); card.addEventListener("click", () => { const names = name.getAnimations().map((animation) => animation.animationName); console.log("Name:", names.join() || "still", "Steam color:", getComputedStyle(steam).backgroundColor); });</script>- The
tea-card.jstab is the overview's card. Line 21 now names two parts:steamandname. - On the page, line 2 declares the page's own keyframes,
blush: the color turns sienna halfway. - Line 3 colors the steam part slate gray.
- Line 4 runs
blushon the name part, only while the card brews. - Lines 12 to 15 print the name's animations and the steam's color on every click.
Press Brew. It prints Name: blush Steam color: rgb(112, 128, 144), and the name blushes while the steam rises. Press Brew again. It prints Name: still, with the same steam color.
Notice where blush lives: in the page. A ::part() rule belongs to the page, so it uses the page's keyframes, as lesson 12.2 noted. Firefox also lets a ::part() rule use the card's own keyframes. Chrome and Safari don't, so don't rely on it.
Animating from JavaScript
CSS isn't the only way. element.animate(), from the Web Animations API, runs keyframes from a script. Animation with JavaScript covers it. A component can call it on its own inner elements:
<tea-card>Green tea</tea-card><button>Brew</button> <script type="module"> import "./tea-card.js"; const card = document.querySelector("tea-card"); document.querySelector("button").addEventListener("click", async () => { const done = card.brew(); console.log("Shadow root:", card.shadowRoot.getAnimations().length); console.log("Host, with subtree:", card.getAnimations({ subtree: true }).length); console.log("Document:", document.getAnimations().length); await done; console.log("Done brewing"); });</script>- In the
tea-card.jstab, lines 1 to 5 are the rise as a list of keyframes.offset: 0.5means halfway. - Line 6 is the gentle version: a fade, with no movement.
- Line 18 asks
matchMedia()about reduced motion.animate()doesn't check it for you. - Line 20 animates the steam twice, 600ms each time, and returns
finished: a promise that resolves when the animation ends. - On the page, line 8 starts brewing. Lines 9 to 11 ask three places for animations. Line 12 waits for the steam, and line 13 prints.
Press Brew. It prints Shadow root: 1, Host, with subtree: 0, and Document: 0. When the steam is done, it prints Done brewing.
Only the shadow root found the steam's animation. getAnimations() on a document or a shadow root lists the animations in that one tree. On an element, { subtree: true } adds its descendants. The Web Animations spec counts descendants in one tree only, and a shadow root is a tree of its own. Why it matters: a page that pauses everything from document.getAnimations() misses what runs inside components. To reach those, ask each open shadow root.
finished is the sure way to know an animation ended. Chrome's motion guidance warns that animationend never fires when reduced motion turns an animation off. Waiting on finished for each animation that getAnimations() lists works either way, even when the list is empty. The kit's card does this in the practical.
Do view transitions work with shadow DOM?
A view transition animates a change to the page. The browser takes a picture of the old state, runs your update, and animates from the old picture to the new one. Each element with a view-transition-name gets its own pictures, in a group named after it. Everything else moves as one group, called root. MDN's guide, the React lesson View transitions, and the web performance lesson View transitions and performance cover the basics.
Can a card name one of its own elements? Try it:
<style> /* The page names nothing. */</style><tea-card>Green tea</tea-card><button>Next tea</button> <script type="module"> import "./tea-card.js"; const groups = () => document.getAnimations() .map((animation) => animation.effect.pseudoElement?.match(/group\((.+)\)/)?.[1]) .filter(Boolean) .sort(); document.querySelector("button").addEventListener("click", async () => { const transition = document.startViewTransition(() => { document.querySelector("tea-card").textContent = "Oolong"; }); await transition.ready; console.log("Groups:", groups().join(", ")); });</script>Press Next tea. It prints Groups: root. Line 2 of the tab names the card's name tea-name, inside its shadow root. The document's transition doesn't see it, so the whole page fades as one picture.
- In the
tea-card.jstab, line 2 names the card's.nameelementtea-name, inside its shadow root. - On the page, line 2 is the only line that changes: a comment, or a
::part(name)rule that gives the same element the same name from the page. - Lines 9 to 12 make
groups(). It reads the name inside each::view-transition-group()from the document's animations, in alphabetical order. - Lines 14 to 16 change the card's text inside
document.startViewTransition(). Line 17 waits until the animations are ready. Line 18 prints.
With the name inside the card, Next tea prints Groups: root. With the page's rule, it prints Groups: root, tea-name. View transition names are tree-scoped too. Chrome's platform status page says it plainly: a transition started on the document can't find names declared inside shadow trees. A name from a ::part() rule comes from the page, so the document finds it.
There's a catch. A page rule names that part in every card. With two cards on the page, both parts get tea-name, and each name may be used only once. Chrome stops the transition with a duplicate name error, and transition.ready rejects.
At a party, the hall's photographer takes before and after photos of the guests on the hall's list. Guests listed only in a private room aren't on that list, so they end up in the crowd shot. A photographer who works inside the room uses the room's own list.
- In real life: The hall's guest list
- In CSS: Names from the page's styles,
::part()rules included - In real life: A private room with its own list
- In CSS: A shadow root and the names declared in it
- In real life: A photographer who works inside the room
- In CSS:
startViewTransition()on an element in the shadow root - In real life: Before and after photos
- In CSS: The old and new pictures in each group
Element-scoped view transitions
Chrome has a second kind. element.startViewTransition() runs a transition on one element and what's inside it. MDN calls it an element-scoped view transition. The rest of the page stays live, and several can run at once. A component can start one on an element inside its own shadow root. Then it finds the names declared there:
<tea-card>Green tea</tea-card><tea-card>Mint</tea-card><button>Next teas</button> <script type="module"> import "./tea-card.js"; const groups = (root) => root.getAnimations() .map((animation) => animation.effect.pseudoElement?.match(/group\((.+)\)/)?.[1]) .filter(Boolean) .sort(); document.querySelector("button").addEventListener("click", async () => { const [first, second] = document.querySelectorAll("tea-card"); const transitions = [first.next("Oolong"), second.next("Chai")]; await Promise.all(transitions.map((transition) => transition?.ready)); console.log("First card:", groups(first.shadowRoot).join(", ") || "none"); console.log("Second card:", groups(second.shadowRoot).join(", ") || "none"); console.log("Document:", groups(document).join(", ") || "none"); });</script>- In the
tea-card.jstab, line 2 names.nametea-name, as before. - Lines 11 to 16 are
next(). Line 12 finds the.cardbox in the shadow root. Line 14 just makes the change in browsers withoutelement.startViewTransition(). Line 15 starts the transition on the box. - On the page, lines 7 to 10 make the same
groups(), but it takes the tree to ask: a shadow root, or the document. Line 13 changes both cards at once. Line 14 waits for both. Lines 15 to 17 print each card's groups, and the document's.
In Chrome it prints First card: root, tea-name, Second card: root, tea-name, and Document: none. Each card's transition found its own tea-name. Two cards used the same name at the same moment, and nothing clashed. The pictures sit on the box, inside each shadow root, so the document lists none. Start it on an inner element, though, not on the host: from the host, Chrome finds only root.
Why don't the names clash? While an element's transition runs, CSS View Transitions 2 gives that element view-transition-scope: all. That property keeps names inside the element's subtree. A component can set it too, so a page's transition never collects its names. Both are in Chrome only. Chrome's team has also proposed a shadowRoots option for startViewTransition(), so a transition could find names inside the shadow roots you pass it.
Adding steam to the tea card
Time to put steam in the kit. First, a quick check. For each card below, the component has :host { transition: all 300ms; }, and brewing changes one value. Does that value move with the host's transition?
- The host's own
background-color, changed by:host(:state(brewing)) - The name's
color, inherited from the host'scolor - The name's
font-size, inherited from the host'sfont-size - The steam's
opacity, set by:host(:state(brewing)) .steam - The name's
color, set right on it by:host(:state(brewing)) h3 - The Brew button's
background-color, set by:host(:state(brewing)) button
Sort each value. The card's only transition is :host { transition: all 300ms; }.
Now the kit. tea-kit/tokens.css gets one more token, --tea-motion: 1;. The base sheet gets the reduced-motion rule:
/** The kit's base styles: one sheet that every component adopts before its own sheet. */
export const base = new CSSStyleSheet();
base.replaceSync(`
@layer base, component, state;
@layer base {
:host { display: block; box-sizing: border-box; }
:host([hidden]) { display: none !important; }
*, *::before, *::after { box-sizing: inherit; }
:where(button) { font: inherit; }
:where(:focus-visible) { outline: 2px solid var(--tea-color-leaf, seagreen); outline-offset: 2px; }
@media (prefers-reduced-motion: reduce) {
:host { --tea-motion: 0; }
}
}
`);Lines 11 to 13 are new. They sit in the base layer, so every component that adopts the base sheet gets --tea-motion: 0 when the person asks for reduced motion. The card gets a steam part, keyframes of its own, and a state that runs them:
.steam { position: absolute; top: 6px; right: 12px; width: 6px; height: 14px; border-radius: 3px; color: var(--tea-color-stone, dimgray); background: currentColor; opacity: 0; pointer-events: none; }
@keyframes tea-card-steam {
from { opacity: 0; translate: 0 0; }
50% { opacity: 1; }
to { opacity: 0; translate: 0 calc(var(--tea-motion, 1) * -16px); }
}
:host(:state(brewing)) .steam { animation: tea-card-steam 600ms ease-out 2; }- Line 1 places the steam at the card's top right, see-through.
pointer-events: nonekeeps it from catching clicks. Its color comes from the stone token, andcurrentColorpaints it, so a page can change it withcolor. - Lines 2 to 6 are the keyframes,
tea-card-steam, in the component layer. Line 5 multiplies the rise by--tea-motion. - Line 7 is in the state layer. While the card brews, the steam rises twice, 600ms each time.
In the markup, <span class="steam" part="steam" aria-hidden="true"> sits at the top of the card. aria-hidden keeps the decoration out of what screen readers read. The .card rule gets position: relative, so the steam is placed against the card. The Add button starts the brewing:
add.addEventListener("click", () => {
this.#brew();
this.dispatchEvent(new TeaAddEvent(this.#tea(), this.#quantity));
});
async #brew() {
this.#internals.states.add("brewing");
const steam = this.shadowRoot.querySelector(".steam");
await Promise.allSettled(steam.getAnimations().map((animation) => animation.finished));
this.#internals.states.delete("brewing");
}- Line 2 starts brewing before line 3 sends
tea-add. So a page that hears the event sees the state already on. - Line 7 turns the state on. Line 9 waits for every animation on the steam to end.
Promise.allSettled()waits for every promise, whether it resolves or rejects. A cancelled animation rejects itsfinishedpromise, and an empty list settles at once. - Line 10 turns the state off.
Here is the kit on a page that styles the steam and the name:
<link rel="stylesheet" href="tea-kit/tokens.css"><style> tea-card::part(steam) { color: slategray; } tea-card::part(name) { transition: color 300ms; } tea-card:state(brewing)::part(name) { color: sienna; }</style><tea-card name="Green tea" price="4"></tea-card> <script type="module"> import "./tea-kit/index.js"; const card = document.querySelector("tea-card"); const steam = card.shadowRoot.querySelector("[part=steam]"); card.addEventListener("tea-add", () => { const names = steam.getAnimations().map((animation) => animation.animationName); console.log("Brewing?", card.matches(":state(brewing)"), "Steam:", names.join() || "none"); });</script>- Line 1 links the kit's tokens. Line 3 colors the steam part slate gray.
- Lines 4 and 5 fade the name to sienna while the card brews: the page's own transition, on a part.
- Line 13 listens for
tea-add. Line 14 lists the steam's animations, and line 15 prints.
Press Add. It prints Brewing? true Steam: tea-card-steam. The steam rises twice and the name turns sienna. When the steam is done, the state goes away and the name fades back. With reduced motion emulated, the steam fades in place, because the base sheet set --tea-motion to 0. At rest, every card looks just as it did in lesson 12.6: the steam is see-through and takes no room.
The card's JSDoc documents the new styling API:
* @cssprop [--tea-motion=1] - How far the steam rises: 1 for full motion, 0 to fade in place. The kit's base sheet sets 0 when the person asks for reduced motion.
* @csspart steam - The steam over the card while it brews. Set its color to change the steam's color.
* @cssstate brewing - The card is brewing a tea someone just added: steam rises, then the state goes away. Only the card sets it.Line 1 is the custom property, with its default of 1. Line 2 is the part, and line 3 is the state. The kit's manifest, custom-elements.json, lists the same three.
Common mix-ups
- "Keyframes from the page work in every component." No. In Chrome, a name inside a shadow root doesn't find the page's keyframes. Declare them in the component's own sheet.
- "A transition on
:hostanimates everything inside." No. It animates the host's own values. Inherited values, likecolor, follow along. Inner elements with values of their own need their own rules. - "Inner elements inherit the host's
transition." No.transitionisn't inherited. An inner element's duration stays0s. - "Reduced motion means turning every animation off." No. It means less or gentler motion. A fade in place keeps the feedback, and WCAG doesn't count it as motion.
- "
element.animate()follows reduced motion by itself." No. CheckmatchMedia()and pick gentler keyframes in your script. - "
document.getAnimations()lists every animation on the page." No. It lists the document's tree only. Ask each open shadow root for its own. - "A
view-transition-nameinside a shadow root works withdocument.startViewTransition()." No. The document doesn't see it. Name the part from the page, or start the transition on an element inside the shadow root.
To check where a motion rule goes, read each row across:
| What you want | Where the rule goes |
|---|---|
| Fade the card's own background. | A transition on :host, in the card's sheet. |
| Fade an element inside the card. | A transition on that element, in the card's sheet. |
| Run keyframes inside the card. | @keyframes in the card's own sheet. |
| Let the page animate a part. | The page's own @keyframes, named in its ::part() rule. |
| Tone motion down. | @media (prefers-reduced-motion: reduce) in the card's sheet, or a switch like --tea-motion. |
| Find a card's animations. | card.shadowRoot.getAnimations(), not the document's. |
| Give an inner element its own view transition group. | Name its part from the page, or start the transition on an element inside the shadow root. |
Practice exercises
Answer first, then use the hints. The pages run live, so you can check yourself.
The card's host fades its color while it brews. What does the page print when you press Brew?
<tea-card>Green tea</tea-card> <script type="module"> import "./tea-card.js"; const card = document.querySelector("tea-card"); const name = card.shadowRoot.querySelector("h3"); card.addEventListener("click", () => console.log("Name's animations:", name.getAnimations().length));</script>Name's animations: 0. The transition runs on the host. The name inherits the host's color at every step, so its color changes smoothly with no animation of its own.
The page names the card's own keyframes on the card's tag. What does Chrome print when you press Brew?
<style> tea-card:state(brewing) { animation: steam-puff 1s infinite; }</style><tea-card>Green tea</tea-card> <script type="module"> import "./tea-card.js"; const card = document.querySelector("tea-card"); const names = (element) => element.getAnimations().map((animation) => animation.animationName).join() || "nothing"; card.addEventListener("click", () => console.log("Host:", names(card)));</script>Host: nothing. steam-puff belongs to the card's shadow root. The page's rule on line 2 can't see it in Chrome, so no animation starts. Firefox lets it through; Safari doesn't.
The steam pops in at once. Change one line of the tea-card.js tab so it fades in. What does it print then?
<tea-card>Green tea</tea-card> <script type="module"> import "./tea-card.js"; const card = document.querySelector("tea-card"); const steam = card.shadowRoot.querySelector(".steam"); card.addEventListener("click", () => { console.log("Steam:", steam.getAnimations().map((animation) => animation.transitionProperty).join() || "nothing"); });</script><tea-card>Green tea</tea-card> <script type="module"> import "./tea-card.js"; const card = document.querySelector("tea-card"); const steam = card.shadowRoot.querySelector(".steam"); card.addEventListener("click", () => { console.log("Steam:", steam.getAnimations().map((animation) => animation.transitionProperty).join() || "nothing"); });</script>The page stays the same. In the tea-card.js tab, line 3 now puts the transition on .steam, the element whose opacity changes. It prints Steam: opacity, and the steam fades in.
Give the steam a gentle version for reduced motion. Then emulate reduced motion in DevTools and press Brew. What does it print?
<tea-card>Green tea</tea-card> <script type="module"> import "./tea-card.js"; const card = document.querySelector("tea-card"); const steam = card.shadowRoot.querySelector(".steam"); card.addEventListener("click", () => { const names = steam.getAnimations().map((animation) => animation.animationName); console.log("Steam:", names.join() || "still"); });</script><tea-card>Green tea</tea-card> <script type="module"> import "./tea-card.js"; const card = document.querySelector("tea-card"); const steam = card.shadowRoot.querySelector(".steam"); card.addEventListener("click", () => { const names = steam.getAnimations().map((animation) => animation.animationName); console.log("Steam:", names.join() || "still"); });</script>The page stays the same. In the tea-card.js tab, lines 11 to 13 swap in steam-fade under reduced motion. Turn it on in DevTools' Rendering tab and press Brew: it prints Steam: steam-fade.
Press Brew, then Pause. It prints Paused: 0, and the steam keeps puffing. Fix the page. What does it print then?
<tea-card>Green tea</tea-card><button>Pause</button> <script type="module"> import "./tea-card.js"; const card = document.querySelector("tea-card"); document.querySelector("button").addEventListener("click", () => { const animations = document.getAnimations(); for (const animation of animations) animation.pause(); console.log("Paused:", animations.length); });</script><tea-card>Green tea</tea-card><button>Pause</button> <script type="module"> import "./tea-card.js"; const card = document.querySelector("tea-card"); document.querySelector("button").addEventListener("click", () => { const animations = card.shadowRoot.getAnimations(); for (const animation of animations) animation.pause(); console.log("Paused:", animations.length); });</script>Line 8 of the page now asks the card's shadow root, where the steam lives. Press Brew, then Pause: it prints Paused: 1, and the steam stops.
Next tea prints Groups: root: the card's name gets no group. Change one line of the tea-card.js tab, not the page. What does Chrome print then?
<tea-card>Green tea</tea-card><button>Next tea</button> <script type="module"> import "./tea-card.js"; const card = document.querySelector("tea-card"); const groups = (root) => root.getAnimations() .map((animation) => animation.effect.pseudoElement?.match(/group\((.+)\)/)?.[1]) .filter(Boolean) .sort(); document.querySelector("button").addEventListener("click", async () => { await card.next("Oolong")?.ready; console.log("Groups:", [...groups(document), ...groups(card.shadowRoot)].join(", ") || "none"); });</script><tea-card>Green tea</tea-card><button>Next tea</button> <script type="module"> import "./tea-card.js"; const card = document.querySelector("tea-card"); const groups = (root) => root.getAnimations() .map((animation) => animation.effect.pseudoElement?.match(/group\((.+)\)/)?.[1]) .filter(Boolean) .sort(); document.querySelector("button").addEventListener("click", async () => { await card.next("Oolong")?.ready; console.log("Groups:", [...groups(document), ...groups(card.shadowRoot)].join(", ") || "none"); });</script>The page stays the same. In the tea-card.js tab, line 15 now starts the transition on the .card box inside the shadow root, so it finds the name declared there. In Chrome it prints Groups: root, tea-name.
Check your understanding
For each question, ask: which tree declares the name, whose value changes, and what does the person ask for?
Question 1 of 7Where should a web component declare the
@keyframesits shadow root uses?Choose an answer to see the explanation.
Question 2 of 7The card's shadow root has this CSS, and the tea's name is an
h3inside it. Right after the card turnsbrewingon, how many animations doesname.getAnimations()list?Read the code, then predict:host { color: black; transition: color 300ms; } :host(:state(brewing)) { color: sienna; } h3 { margin: 0; }Choose an answer to see the explanation.
Question 3 of 7Someone asks for reduced motion. Which feedback can the card still show?
Choose an answer to see the explanation.
Question 4 of 7The steam animates inside the card's open shadow root. What does
card.getAnimations({ subtree: true })give back?Choose an answer to see the explanation.
Question 5 of 7A card's own sheet gives its name
view-transition-name: tea-name. The page callsdocument.startViewTransition(). Which groups animate?Choose an answer to see the explanation.
Question 6 of 7Does
element.animate()followprefers-reduced-motionby itself?Choose an answer to see the explanation.
Question 7 of 7Two cards are on the page. The page writes
tea-card::part(name) { view-transition-name: tea-name; }and starts a document view transition. What happens in Chrome?Choose an answer to see the explanation.
Key takeaways
- Declare a component's keyframes and transitions in its own shadow root. Keyframes there work inside and on
:host. - In Chrome, a name inside a shadow root doesn't find the page's keyframes. A
::part()rule uses the page's. - A transition on
:hostanimates the host's own values. Inherited values follow, buttransitionisn't inherited, so inner elements need their own rules. - Reduced motion means less motion, not no feedback. Swap movement for a fade inside
@media (prefers-reduced-motion: reduce), and checkmatchMedia()in scripts. - One base-sheet rule can set a kit-wide
--tea-motionto 0, and a page can offer its own switch. - Start motion from a custom state. Find a component's animations with
shadowRoot.getAnimations(), and wait onfinished. - A document view transition ignores names inside shadow roots. Name the part from the page, or start an element-scoped transition inside, in Chrome.
Remember the one-liner.
The card carries its own motion, a state starts it, and a person who asks for less gets a fade, not a rise.
Sources
The facts on this page come from these standards, docs, and posts:
- transition, MDN.
- opacity, MDN.
- CSS Shadow Module Level 1: Name-defining constructs and inheritance, W3C CSS Working Group.
- Author-defined CSS names and the shadow DOM, Chrome for Developers.
- Modern CSS Feature Support For Shadow DOM: @keyframes, Adobe Spectrum Web Engineering.
- prefers-reduced-motion, MDN.
- Understanding SC 2.3.3: Animation from Interactions, W3C WAI.
- Motion, Chrome for Developers, Modern Web Guidance.
- Emulate CSS media features, Chrome DevTools docs.
- CTA Modal: How To Build A Web Component, Nathan Smith, Smashing Magazine.
- ShadowRoot: getAnimations(), MDN.
- Web Animations Level 1: relevant animations for a subtree, W3C CSS Working Group.
- View transitions, MDN.
- View Transitions: shadowRoots option in startViewTransition(), Chrome Platform Status.
- Using element-scoped view transitions, MDN.
- view-transition-scope, MDN.
- CSS View Transitions Module Level 2: view-transition-scope, W3C CSS Working Group.
Coming next: Accessibility and shadow DOM, the first lesson of Accessible components. Screen readers read the flat tree, and the next stage starts there.