When to skip shadow DOM
Shadow DOM vs light DOM: see what shadow DOM costs in forms, global CSS, fonts, and labels, how to mix the two, and a checklist for choosing one.
- 01Name what shadow DOM costsForms, global CSS, fonts, labels, page scripts, and server rendering all stop at a shadow root. Speed depends on the page.
- 02Build without it, or mixWrite a light DOM component with
@scopefor its own rules, or keep only a component's frame and buttons in a shadow root. - 03Choose with a checklistAsk a few questions about each component, and pick light DOM, shadow DOM, or both.
When should you skip shadow DOM?
Leaf and Kettle's checkout has a new part. Ravi built a cups box, <tea-order>, with a shadow root. Asha put it in the checkout form, next to the tea box. The first orders came in that evening. Every one had a tea. Not one had the number of cups.
"Where did the cups go?" Asha asks. A bigger question follows. When should a component skip shadow DOM?
Skip shadow DOM when a component's content must act like the page's own. Its inputs must join the page's form, or it must follow the site's CSS, fonts, and labels. Keep shadow DOM for parts that must look and work the same on any page, and mix the two when a component needs both.
Here is the checkout, cut down to one tea and the cups box. Press Order in the result:
<form> <input name="tea" value="Oolong"> <tea-order></tea-order> <button>Order</button></form> <script src="tea-order.js"></script><script> const form = document.querySelector("form"); form.addEventListener("submit", (event) => { event.preventDefault(); for (const [name, value] of new FormData(form)) { console.log(name, value); } });</script>- Lines 1 to 5 are the form. Line 2 is the tea box, with Oolong in it. Line 3 is Ravi's cups box. Line 4 sends the form.
- The
tea-order.jstab holds the class. Its line 5 puts a label and an input namedcups, with the value 2, inside the shadow root. - Back on the page, line 10 runs code when the form is sent. Line 11 stops the browser from loading a new page.
- Line 12 collects the form's data with
new FormData(form). AFormDataobject holds one entry for each input the form sends: its name and its value. Line 13 prints each entry.
Press Order. The console prints tea Oolong, and nothing else. The cups box is on the screen with a 2 in it, but the form never sent it. FormData, on the JavaScript path, covers the object itself.
That's one cost of shadow DOM. Lesson 6.3 showed that a shadow root keeps its own ids, styles, and searches. Most of the time, that protects a component. But the same wall keeps out things a component may need. Here are four of them:
The page's own tree is called the light DOM. It holds the elements the page wrote, and anything a component adds without a shadow root. Lesson 5.5 met it.
A family puts a lock on the medicine cabinet. The little ones can't open it by accident, and that's the point. Nobody puts a lock on the fridge. Everyone needs the milk many times a day. Fetching a key each time would make no sense.
- In real life: The lock
- In JavaScript: A shadow root
- In real life: The medicine cabinet
- In JavaScript: A widget whose insides nobody should touch by accident
- In real life: The fridge
- In JavaScript: Content the page must style, send, label, and search
- In real life: Fetching the key every time
- In JavaScript: Extra code to reach inside: form APIs, shared style sheets, ARIA tricks
Shadow DOM is a wall with costs. It keeps out accidents, and it also keeps out the page's form, global CSS, labels, and scripts. Use it for a component's private parts. Keep anything the page must style, send, label, or search in the light DOM.
The next sections prove each cost in Chrome, one at a time. Then come the ways around them: light DOM components, @scope, and mixing.
Do inputs in shadow DOM submit with a form?
No. An input inside a shadow root doesn't belong to any form on the page. The browser leaves it out of everything the form does.
Why? Each input has a form owner: the form it belongs to. The HTML Standard says how the browser finds it. It looks at the input's parent, then that one's parent, and so on. The nearest <form> it meets is the owner. From the cups box, the climb reaches the label, then the shadow root, and stops there. It never meets the form.
FormData only gets the tea.This page asks the form what it knows about the cups box. This time, the cups input is required and empty:
<form> <input name="tea" value="Oolong"> <tea-order></tea-order> <button>Order</button></form> <script src="tea-order.js"></script><script> const form = document.querySelector("form"); const cups = document.querySelector("tea-order").shadowRoot.querySelector("input"); console.log(cups.form); console.log(form.elements.length); console.log(form.checkValidity());</script>- In the
tea-order.jstab, line 5 makes the cups inputrequired, with no value. A required input must be filled in before its form can be sent. - Line 10 finds the input through the component's open shadow root.
- Line 11 prints the input's form owner:
null. - Line 12 prints
2. A form'selementslists the controls it owns: the tea box and the Order button. - Line 13 asks the form whether every control it owns is filled in correctly. It prints
true, though the required cups box is empty.
The course also sent this form for real, in Chrome, and found the same gap everywhere:
- The address the form loaded was
order?tea=Oolong. The cups weren't in it. - The empty, required cups box didn't stop the order. The same box in the page's tree did.
form.reset()put the tea box back to Oolong. The cups box kept what was typed in it.- Pressing Enter in the cups box didn't send the form. Enter in the tea box did.
A waiter carries a tray to the till. The cashier counts every cup standing on it. One cup sits inside a closed lunchbox on the tray. The cashier never opens lunchboxes, so that cup never reaches the bill.
- In real life: The tray
- In JavaScript: The
<form> - In real life: Cups standing on the tray
- In JavaScript: Inputs in the page's tree, inside the form
- In real life: A cup inside a closed lunchbox
- In JavaScript: The cups input inside the shadow root
- In real life: The bill
- In JavaScript:
FormData, and what the form sends
Why it matters: the form looks fine and sends too little. No error appears anywhere. You find out from the orders. There are three ways out:
- Keep the input in the light DOM. Lesson 5.6 wrapped a real form this way, and it worked with no script at all.
- Keep the input in the light DOM, and show it through a slot. The section on mixing does this.
- Make the component a form control itself, with form-associated custom elements. It then sends its own value, like an input. They have been Baseline widely available since September 2025. The lesson on joining a form, in Forms, teaches them.
Form validation, on the JavaScript path, covers required and checkValidity().
Why don't global styles work inside shadow DOM?
Most sites have one stylesheet for the whole page. It often holds four kinds of rules:
- a reset, which evens out the browser's defaults, like
box-sizing: border-box; - utility classes, small classes that each do one job, like
.p-4for padding. Tailwind CSS is built from them; - theme rules, which give buttons, links, and headings the site's look;
- focus styles, which draw the ring around whatever has keyboard focus.
Lesson 6.3 showed that page selectors stop at a shadow root. So none of these rules reach inside. Try each one. The card's shadow root holds the same box and button as the page:
<style> *, *::before, *::after { box-sizing: border-box; }</style><div class="p-4"><button>Page button</button></div><tea-card></tea-card> <script src="tea-card.js"></script><script> const card = document.querySelector("tea-card").shadowRoot; for (const [where, root] of [["Page:", document], ["Card:", card]]) { const element = root.querySelector("div"); console.log(where, getComputedStyle(element).boxSizing); }</script>Many sites start with this reset, so a box's width includes its padding. It never reaches the card's box. A page rule only matches elements in the page's own tree, even when it uses *.
- Line 2 holds the page's rule. Each choice puts a different one there.
- Line 4 is the page's box, with the class
p-4, and a button. Thetea-card.jstab puts the same box and button in the card's shadow root. - Line 9 gets the card's shadow root.
- Lines 10 to 13 visit the page, then the card. Line 11 finds the box or the button in each. Line 12 prints one of its computed styles.
Pick A utility class. It prints Page: 16px and Card: 0px. The card's box has the class, but the page's .p-4 rule can't select it. Now pick An inherited color. Both print rgb(139, 69, 19). Inherited values cross into a shadow root. Rules that select elements stop.
Focus styles stop too. In Chrome, a page rule like :focus-visible { outline: 3px solid crimson; } draws its ring on the page's button. When Tab reaches the card's button, it gets the browser's own ring instead. Manuel Matuzović met this, and had to repeat his focus styles in every component. Heydon Pickering of Every Layout found that box-sizing doesn't reach in. Mayank describes adding the reset to every shadow tree, while utility classes stay behind outside.
A hotel's housekeeping stocks every room the same way: white towels, a reading lamp, a welcome card. One suite on the top floor is run by another company. Housekeeping never goes in. If the suite wants towels, it must bring its own.
- In real life: Housekeeping
- In JavaScript: The page's global stylesheet
- In real life: The same towels and lamp in every room
- In JavaScript: Resets, utility classes, theme rules, focus styles
- In real life: The suite run by another company
- In JavaScript: A component's shadow root
- In real life: Bringing its own towels
- In JavaScript: A
<style>inside every shadow root - In real life: One shared store cupboard
- In JavaScript: One constructable style sheet that every shadow root adopts
Why it matters: with shadow DOM, a component must bring every style it needs. It repeats the site's rules inside, or the site shares them on purpose. Constructable style sheets let many shadow roots share one sheet. Lesson 11.5, Constructable stylesheets, teaches them. For colors and sizes, custom properties cross the boundary, as lesson 2.3 showed.
Does @font-face work in shadow DOM?
A web font needs two parts:
- an
@font-facerule, which gives the font a name and says where its file is; - a
font-familyproperty, which uses that name.
In Chrome, an @font-face rule inside a shadow root does nothing. This card declares its own font, Card Hand. The page declares Leaf Serif:
<style> @font-face { font-family: "Leaf Serif"; src: url(leaf-serif.woff2); }</style><tea-card></tea-card> <script src="tea-card.js"></script><script> for (const face of document.fonts) { console.log(face.family); }</script>- Line 2 declares Leaf Serif on the page.
- In the
tea-card.jstab, line 7 declares Card Hand, inside the card's shadow root. Line 8 uses it for the card's paragraph. - On the page,
document.fontsis the list of fonts the page knows. Lines 8 to 10 print the name of each one.
In Chrome, it prints only Leaf Serif. Card Hand never joined the list. The course also tried this with a real font file. The card's paragraph stayed in its fallback font. Then the same @font-face rule moved to the page, and the card's paragraph got the new font.
That second result is the way out. The CSS Shadow spec says a font named in the page can be used inside every shadow root below it. So declare fonts in the page, and let components use them with font-family. Safari does take an @font-face inside a shadow root, but treats it as if the page had written it. Chrome's article on CSS names reports this. Only the page works the same in every browser.
Why it matters: a component that ships its own font has to ask the page to declare it. Fonts and shadow DOM, lesson 11.7, goes deeper, with icon fonts and fallbacks.
What else stops at the shadow boundary?
Three more things stop there: id references, scripts written for the page, and HTML from the server.
Labels and ARIA references
Lesson 6.3 showed that a <label for> on the page can't name an input inside a component. Neither can aria-labelledby or aria-describedby. An id reference only looks in its own tree.
Part of this is solved. Element references, like input.ariaLabelledByElements, can point from inside a shadow root out to the page. MDN says the target must be in the same tree or a parent tree. They work in Chrome 135, Firefox 136, and Safari 16.4.
Pointing into a shadow root is harder. Reference Target lets a host pass id references on to an element inside it. It's on by default only in Chrome, since version 152. Firefox and Safari have it behind a setting. The lesson on ARIA references across shadow roots, in Accessible components, teaches both.
Scripts and tools that search the page
Pages run scripts that other people wrote: analytics, A/B tests, chat widgets. Many of them search the page with querySelectorAll(), or listen for clicks on document. Lesson 6.1 showed that such searches stop at a shadow root. Here is a small tracking script:
<button data-track="menu">See the menu</button><tea-card></tea-card> <script src="tea-card.js"></script><script> // A tracking script, written for the page console.log(document.querySelectorAll("[data-track]").length); document.addEventListener("click", (event) => { const tracked = event.target.closest("[data-track]"); console.log("Tracked:", tracked ? tracked.dataset.track : "nothing"); });</script>- Line 1 is a page button with
data-track="menu". Thetea-card.jstab puts a second tracked button, Add Green tea, in the card's shadow root. - Line 7 counts the tracked buttons it can find. It prints
1. - Lines 8 to 11 listen for clicks on the page. Line 9 climbs from the clicked element to the nearest one with
data-track.
Click See the menu: Tracked: menu. Click Add Green tea: Tracked: nothing. The page sees the click come from the card, not from its button, as lesson 6.3 showed. The card itself has no data-track. So the tracker never learns that someone added a tea.
Lightning Web Components, Salesforce's framework, gives this as a reason to offer light DOM: it lets third-party tools find elements with querySelector() and querySelectorAll(). Some tools do look inside. Playwright finds elements in open shadow roots, and browser extensions have a way in, as lesson 6.2 showed. Exercise 6 fixes this tracker. The lesson on testing through shadow roots, in Testing, tooling, and publishing, covers tests.
Server rendering
A server sends HTML. Light DOM content is HTML already, so it shows as soon as it arrives. A shadow root from attachShadow() only exists once the script runs. Lesson 2.5 showed both, and the fix: declarative shadow DOM. It's a <template shadowrootmode> that the browser turns into a shadow root while it reads the HTML. It has been Baseline widely available since August 2026.
One cost stays. With declarative shadow DOM, every copy of a component carries its own <template> in the HTML. Server rendering covers it in full.
Is shadow DOM faster than light DOM?
Sometimes. It depends on the page and the browser. To draw a page, the browser works out which CSS rules match which elements. This is called style calculation. More rules and more elements mean more work. A shadow root splits the work up: its rules only need checking against the elements in that root.
Nolan Lawson measured this in 2022, with 1,000 components on one page, on his own laptop. In Chrome 102, plain global CSS took 1,022 milliseconds of style calculation. The same page with shadow DOM took 49. Scoping with class names, the way Vue and Svelte do, took between 48 and 357, depending on how the styles were added. Firefox was fast in every case.
He called shadow DOM "the most consistently performant option". Class-based scoping beat it slightly in some cases. And he advised against choosing either one for speed.
Shadow DOM has a cost of its own. Each copy of a component holds its own copy of its styles. Chrome's guide says a <style> in every shadow root is "duplicated per instance". Count them here:
<tea-card></tea-card><tea-card></tea-card><tea-card></tea-card> <script src="tea-card.js"></script><script> const cards = document.querySelectorAll("tea-card"); let sheets = 0; for (const card of cards) sheets += card.shadowRoot.styleSheets.length; console.log(document.styleSheets.length); console.log(sheets); console.log(cards[0].shadowRoot.styleSheets[0] === cards[1].shadowRoot.styleSheets[0]);</script>- Lines 1 to 3 are three cards. The
tea-card.jstab gives each shadow root its own<style>. - Line 9 adds up the style sheets in the three roots.
styleSheetslists the sheets of a document or a shadow root. - Line 10 prints
0: the page itself has none. Line 11 prints3: one per card. - Line 12 prints
false. The first two cards hold two different sheet objects.
The same three teas in light DOM need one rule on the page, so the page holds one sheet. A hundred cards in shadow roots hold a hundred sheets. A constructable style sheet fixes that: one sheet, adopted by every root.
Why it matters: don't pick light DOM or shadow DOM for speed alone. Measure your own page, and share one sheet when a component has many copies. The lesson on what web components cost, in Applications and performance, measures components in DevTools.
How do you build a component without shadow DOM?
Leave out attachShadow(). The class works on the element's own children instead, as in lessons 5.5 and 5.6. Its markup is the page's markup, so every cost above disappears.
Libraries allow it too. Lit, a popular library for web components, renders into a shadow root by default. A Lit component can override a method called createRenderRoot() and return this. Then Lit renders into the element's own children. Lit's docs call this "generally not recommended", and say what you give up. The element loses its DOM and style scoping. And it can't "compose elements into its internal DOM". That last part means slots.
A slot only works inside a shadow root. Try one in the light DOM:
<tea-box> <slot>Nothing here yet</slot> <p>Green tea</p></tea-box> <script> customElements.define("tea-box", class extends HTMLElement {}); console.log(document.querySelector("slot").assignedNodes().length);</script>- Lines 1 to 4 put a
<slot>and a paragraph insidetea-box. - Line 7 defines
tea-boxwith an empty class. It has no shadow root. - Line 8 asks the slot how many nodes were assigned to it. It prints
0.
The result shows Nothing here yet, then Green tea. Here the slot is a plain element. It shows its own content, and the paragraph stays where it is. The DOM Standard's steps for filling a slot stop at once when the slot isn't in a shadow root.
So a light DOM component gives up three things:
- Its styles aren't kept apart from the page's.
- Page scripts can reach and change its insides.
- It has no slots.
The next section deals with the first one.
Can @scope replace shadow DOM?
Partly. @scope is a CSS rule that limits other rules to one part of the page. Write @scope (tea-note) { … }, and the rules inside it only match elements inside a tea-note.
<style> body { color: saddlebrown; } .p-4 { padding: 16px; } @scope (tea-note) { p { color: seagreen; } }</style><p class="p-4">Page tea</p><tea-note><p class="p-4">Green tea</p></tea-note> <script> customElements.define("tea-note", class extends HTMLElement {}); const [page, note] = document.querySelectorAll("p"); console.log(getComputedStyle(page).color); console.log(getComputedStyle(note).color); console.log(getComputedStyle(note).padding);</script>- Line 2 gives the page saddlebrown text. Line 3 is a utility class.
- Lines 4 to 6 are the note's own rule, scoped to
tea-note: its paragraphs are sea green. - Line 8 is a page paragraph. Line 9 is a paragraph inside the note. Both have the class
p-4. - Line 12 defines
tea-note, with no shadow root. - Lines 14 to 16 print
rgb(139, 69, 19),rgb(46, 139, 87), and16px.
Page tea stays saddlebrown, so the note's rule didn't leak out. Green tea turns sea green, and it still gets the page's padding. Press Edit & run and delete lines 4 and 6, the @scope line and its closing brace. Now Page tea turns sea green too.
So @scope works in one direction. It keeps a component's rules in. It doesn't keep the page's rules out. MDN adds that inherited values, like color, still flow past a scope's edge. A component can also put @scope { … }, with no selector, in a <style> inside itself. Its rules then apply inside that <style>'s parent element.
A family pins a sign on the playroom door: shoes off in here. That rule only counts in that room. But the house rules still count in the playroom: no running on the stairs, lights off at nine. The guest cottage in the garden is different. The house rules stop at its door.
- In real life: The playroom
- In JavaScript: The element
@scopenames,tea-note - In real life: "Shoes off in here"
- In JavaScript: The note's own rules
- In real life: The house rules
- In JavaScript: The page's CSS, which still reaches in
- In real life: The guest cottage
- In JavaScript: A component with a shadow root
Why it matters: a component that should follow the site's look often needs nothing more than @scope. It works in every current browser, and became Baseline in March 2026, with Safari 26.4. The lesson on page styles for components, in Styling web components, uses it more.
Can you mix light DOM and shadow DOM?
Yes. A component can keep its content in the light DOM, and put only its own parts in a shadow root: a frame, some buttons, a layout. A <slot> in the shadow root shows the light DOM content in the right place. Theresa O'Connor argues for this split. Keep the page's markup as clean as its content needs, and put the extra boxes and controls a design needs in the shadow DOM.
Ravi rebuilds the cups box as a stepper, with a minus and a plus button. The page writes the input. The stepper adds the buttons:
<style> input { width: 48px; color: crimson; }</style><form> <label for="cups">Cups</label> <tea-stepper> <input id="cups" name="cups" type="number" value="2" min="1" max="5"> </tea-stepper> <button>Order</button></form> <script src="tea-stepper.js"></script><script> const form = document.querySelector("form"); console.log(document.querySelectorAll("button").length); form.addEventListener("submit", (event) => { event.preventDefault(); console.log("Order:", new FormData(form).get("cups"), "cups"); });</script>- Line 2 is the page's CSS for inputs: 48 pixels wide, with crimson text.
- Line 5 is the page's label for
cups. Line 7 is the input itself, written by the page insidetea-stepper. It takes a number from 1 to 5. - Line 15 counts the buttons on the page. It prints
1: only Order. - Lines 16 to 19 print the cups when the form is sent.
In the tea-stepper.js tab:
- Line 7 styles the buttons. Only the stepper's own rules can reach them.
- Lines 9 and 11 are the two buttons. Each has an
aria-label, the words a screen reader says for it. Line 10 is the slot, between them. - Line 12 listens for clicks inside the shadow root. Line 13 finds the input among the stepper's own children.
- Lines 14 and 15 call
stepDown()orstepUp(). They move a number box down or up by one, and stay betweenminandmax.
Press + and then Order. The console prints Order: 3 cups. Press + three more times, and it stops at 5. Click the word Cups, and the cursor jumps into the box. Now press Edit & run and delete line 12, the line that loads the stepper. The buttons disappear, and a plain number box is left. Order still sends the cups.
<slot>. The input stays the stepper's child in the page's tree, so the form, the label, and the page's CSS still find it.The split is the point. Everything the page needs stays in its tree. The form, the label, the page's CSS, and page scripts all find the input. The buttons are the stepper's own. Page CSS can't restyle them, and page scripts can't find them. The lesson on placing content with slots, later in Shadow DOM, templates, and slots, teaches slots in full.
A tea supplier gives Leaf and Kettle a display stand. The frame, the sign, and the little lights are the supplier's. The shop fills the shelves with its own tins. Each tin keeps the shop's price label, and each one is counted at the stocktake.
- In real life: The stand's frame, sign, and lights
- In JavaScript: The stepper's buttons and styles, in its shadow root
- In real life: The shelf
- In JavaScript: The
<slot> - In real life: The shop's own tins
- In JavaScript: The page's input, in the light DOM
- In real life: The shop's price labels
- In JavaScript: The page's CSS
- In real life: The stocktake
- In JavaScript: The form, the label, and page scripts
Now compare all three ways on one cups box. Each choice changes one line in the component:
<style> input { color: crimson; }</style><form> <label for="cups">How many?</label> <tea-cups> <input id="cups" name="cups" type="number" value="2"> </tea-cups></form> <script> const form = document.querySelector("form"); const cups = document.getElementById("cups"); customElements.define("tea-cups", class extends HTMLElement { connectedCallback() { // No shadow root: the input stays where the page put it. } }); console.log("Sent with the form:", new FormData(form).has("cups")); console.log("Named by the label:", cups.labels.length === 1); console.log("Colored by page CSS:", getComputedStyle(cups).color === "rgb(220, 20, 60)"); console.log("Found by page scripts:", document.querySelector("#cups") !== null);</script>The component leaves its child alone. The input is part of the page, so the form sends it, the label names it, the page's CSS colors it, and page scripts find it.
Light DOM and the slot both print true four times. The shadow root prints false four times. The box looks much the same on the screen each time. What changes is the tree it lives in.
How do you choose between shadow DOM and light DOM?
Ask a few questions about each component. Read each row across: a question, what a yes points to, and why.
| Ask | If yes | Why |
|---|---|---|
| Is it content the page owns, like text, a list, or an article? | Light DOM. | The page's CSS, fonts, and scripts reach it, and the server sends it as plain HTML. |
| Does it hold inputs for a form on the page? | Light DOM, or a slot. | An input inside a shadow root doesn't join the page's form. |
| Must it follow the site's resets, utility classes, and theme? | Light DOM, with @scope for its own rules. | Global rules don't select anything inside a shadow root. |
| Must it show before JavaScript runs? | Light DOM, or declarative shadow DOM. | A root from attachShadow() only exists once the script runs. |
| Do page labels, ARIA, or page scripts need to reach its insides? | Light DOM, or a slot. | Id references and searches stop at the shadow boundary. |
| Will it run on pages you don't control, and must it look the same there? | Shadow DOM. | The page's rules can't break its look, and its own rules can't leak out. |
| Does it place the page's content inside a layout of its own? | Shadow DOM, with slots. | Slots only work inside a shadow root. |
Back to the medicine cabinet and the fridge: lock only what needs a lock. Most components fall clearly on one side. Some have a private part and a public part, and get both. Lesson 1.3 gave the same choice from the other side: who should be able to restyle the inside, the page or the component's author?
Now sort some components by the checklist:
- A pull quote on a blog, in the blog's own fonts and colors
- A search box around a form that must work without JavaScript
- A menu that wraps the site's own links
- A star rating that forty partner sites embed
- A date picker in a design system that many apps use
- A cups box with - and + buttons, inside a checkout form
- A product card: the shop's own name and price, in a fixed frame
Sort each component by where its markup should live.
Choosing for each part of the tea kit
Run the checklist on the tea kit you've built so far. This page loads the whole kit, and asks each component where its markup lives:
<tea-label name="Green tea" minutes="3"></tea-label><tea-price amount="4"></tea-price><tea-timer seconds="180"></tea-timer><tea-menu> <tea-item price="4">Green tea</tea-item> <tea-item price="3">Black tea</tea-item></tea-menu><tea-filter> <form><input type="search" name="q" aria-label="Search teas"></form> <ul><li>Green tea</li><li>Black tea</li></ul></tea-filter><tea-card name="Oolong" price="5"></tea-card> <script type="module"> import "./tea-kit/index.js"; for (const tag of ["tea-label", "tea-price", "tea-timer", "tea-menu", "tea-filter", "tea-card"]) { const where = document.querySelector(tag).shadowRoot ? "shadow DOM" : "light DOM"; console.log(tag, where); }</script>- Lines 1 to 12 use the kit's components, with their usual attributes and children.
- Line 15 loads the whole kit.
- Lines 17 to 20 check each tag for a shadow root, and print where its markup lives.
It prints light DOM five times, then tea-card shadow DOM. Read each row across to see why each one fits the checklist:
| Component | Where its markup lives | Why |
|---|---|---|
tea-label, tea-price | Light DOM. | They write one line of text into a page. The page's fonts and colors should apply. |
tea-timer | Light DOM. | Its countdown is plain text in the page. Nothing in it needs protecting. |
tea-menu and tea-item | Light DOM. | The server sends the teas as HTML, and the page's CSS styles them. |
tea-filter | Light DOM. | It wraps a real form, which must work and send its search without JavaScript. |
tea-card | Shadow DOM. | Its frame must look the same on every page. Its name and price are content, so they could move to the light DOM with slots. |
Only the card has a shadow root, and its frame earns it. Its name and price are another matter. They are the shop's content, so they could stay in the light DOM and show through slots, like the stepper's input. Lines 17 to 20 work on any page, too. Paste them into the console of a site you use, with that site's own tag names.
Common mix-ups
- "Shadow DOM breaks accessibility, period." No. Labels and ARIA work inside one shadow root, and element references can point out of it. Only pointing in is hard, and Reference Target handles that in Chrome.
- "Cross-root ARIA is solved." No. Reference Target is on by default only in Chrome 152 and later. Firefox and Safari have it behind a setting.
- "Shadow DOM components can't be server-rendered." No. Declarative shadow DOM sends a shadow root in the HTML, in every current browser.
- "Shadow DOM is always faster, or always slower." No. Nolan Lawson found it consistently fast, and class-based scoping was about as fast in some cases.
- "@scope keeps the page's styles out, like a shadow root." No. It keeps a component's rules in. The page's
.p-4still reached the note. - "Custom fonts can't be used inside a shadow root." No. A font declared in the page works inside. Only an
@font-facerule inside the shadow root is ignored, in Chrome.
Practice exercises
Answer first, then use the hints. Each result runs live, so you can check yourself.
How many entries does the page print?
<form> <input name="tea" value="Oolong"> <input name="milk" value="oat"> <tea-order></tea-order></form> <script src="tea-order.js"></script><script> const form = document.querySelector("form"); console.log([...new FormData(form)].length);</script>2. The tea and the milk are in the form's tree. The cups input is inside the shadow root, so FormData leaves it out.
What padding does the page print for the card's paragraph?
<style> .p-4 { padding: 16px; }</style><tea-card></tea-card> <script src="tea-card.js"></script><script> const name = document.querySelector("tea-card").shadowRoot.querySelector("p"); console.log(getComputedStyle(name).padding);</script>0px. The page's .p-4 rule only matches elements in the page's tree. The class inside the card is the card's own.
Change the page and tea-order.js so Order sends the cups too. What does the second line print?
<form> <input name="tea" value="Oolong"> <tea-order></tea-order> <button>Order</button></form> <script src="tea-order.js"></script><script> const form = document.querySelector("form"); form.addEventListener("submit", (event) => { event.preventDefault(); for (const [name, value] of new FormData(form)) { console.log(name, value); } });</script><form> <input name="tea" value="Oolong"> <tea-order><input name="cups" value="2"></tea-order> <button>Order</button></form> <script src="tea-order.js"></script><script> const form = document.querySelector("form"); form.addEventListener("submit", (event) => { event.preventDefault(); for (const [name, value] of new FormData(form)) { console.log(name, value); } });</script>Press Order, and it prints tea Oolong, then cups 2. The input is now the page's, so the form owns it. The slot only shows it inside the component. Dropping the shadow root also works.
In Chrome, the page prints 0: the card's font never joined the page's list. Fix it. What does the page print then?
<tea-card></tea-card> <script src="tea-card.js"></script><script> console.log(document.fonts.size);</script><style> @font-face { font-family: "Card Hand"; src: url(card-hand.woff2); }</style><tea-card></tea-card> <script src="tea-card.js"></script><script> console.log(document.fonts.size);</script>In Chrome, it prints 1. The page now declares Card Hand, so it joins document.fonts, and the card can use it by name. Inside the shadow root, Chrome ignored it.
The note's paragraph should get the page's .p-4 padding and stay sea green. Rewrite it as a light DOM component. What does the page print?
<style> .p-4 { padding: 16px; }</style><tea-note></tea-note> <script src="tea-note.js"></script><script> const note = document.querySelector("tea-note"); const name = (note.shadowRoot ?? note).querySelector("p"); console.log(getComputedStyle(name).padding);</script><style> .p-4 { padding: 16px; } @scope (tea-note) { p { color: seagreen; } }</style><tea-note><p class="p-4">Green tea</p></tea-note> <script src="tea-note.js"></script><script> const note = document.querySelector("tea-note"); const name = (note.shadowRoot ?? note).querySelector("p"); console.log(getComputedStyle(name).padding);</script>It prints 16px. The paragraph is in the light DOM, so the page's utility class reaches it. @scope keeps the sea green rule inside the note.
Change line 9 so the tracker also hears Add Green tea, without touching the card. What does a click on it print?
<button data-track="menu">See the menu</button><tea-card></tea-card> <script src="tea-card.js"></script><script> // A tracking script, written for the page console.log(document.querySelectorAll("[data-track]").length); document.addEventListener("click", (event) => { const tracked = event.target.closest("[data-track]"); console.log("Tracked:", tracked ? tracked.dataset.track : "nothing"); });</script><button data-track="menu">See the menu</button><tea-card></tea-card> <script src="tea-card.js"></script><script> // A tracking script, written for the page console.log(document.querySelectorAll("[data-track]").length); document.addEventListener("click", (event) => { const tracked = event.composedPath().find((node) => node.dataset?.track); console.log("Tracked:", tracked ? tracked.dataset.track : "nothing"); });</script>It prints Tracked: add. The card's root is open, so the path starts at the inner button. find() returns the first node with a data-track. The ?. skips nodes like document, which have no dataset.
Check your understanding
For each question, ask which tree the element lives in, and which tree the rule or the form looks at.
Question 1 of 7In the opening example, you click Order. What does the console print?
Read the code, then predict<form> <input name="tea" value="Oolong"> <tea-order></tea-order> <button>Order</button> </form> <script src="tea-order.js"></script> <script> const form = document.querySelector("form"); form.addEventListener("submit", (event) => { event.preventDefault(); for (const [name, value] of new FormData(form)) { console.log(name, value); } }); </script>Choose an answer to see the explanation.
Question 2 of 7The cups input is
requiredand empty, inside a shadow root in the form. What doesform.checkValidity()return?Read the code, then predict<form> <input name="tea" value="Oolong"> <tea-order></tea-order> <button>Order</button> </form> <script src="tea-order.js"></script> <script> const form = document.querySelector("form"); const cups = document.querySelector("tea-order").shadowRoot.querySelector("input"); console.log(cups.form); console.log(form.elements.length); console.log(form.checkValidity()); </script>Choose an answer to see the explanation.
Question 3 of 7The page has
.p-4 { padding: 16px; }. A<div class="p-4">inside a card's shadow root has what padding?Choose an answer to see the explanation.
Question 4 of 7A component needs a handwriting font. Where should its
@font-facerule go so it works in Chrome?Choose an answer to see the explanation.
Question 5 of 7What does
@scope (tea-note) { p { color: seagreen; } }do?Choose an answer to see the explanation.
Question 6 of 7In the stepper, the page's
<input>shows through a<slot>in the shadow root. Does the form send it?Choose an answer to see the explanation.
Question 7 of 7What did Nolan Lawson's 2022 benchmark find about shadow DOM and style speed?
Choose an answer to see the explanation.
Key takeaways
- Shadow DOM is a wall. It keeps out accidents, and also the page's form, global CSS, labels, and scripts.
- An input inside a shadow root has no form owner.
FormData, validation, reset, and Enter all skip it. - Resets, utility classes, theme rules, and focus styles stay outside. Only inherited values and custom properties cross.
- In Chrome,
@font-faceinside a shadow root does nothing. Declare fonts in the page. - Speed depends on the page. Each shadow root holds its own copy of its styles.
- A light DOM component keeps the page's CSS and scripts.
@scopekeeps its own rules in, but not the page's out. Slots need a shadow root. - Mixing works: the frame and buttons in a shadow root, the content in the light DOM through a slot.
Remember the one-liner.
Use shadow DOM for a component's private parts, and keep anything the page must style, send, label, or search in the light DOM.
Sources
The facts on this page come from these standards, docs, and posts:
- HTML Standard: reset the form owner, WHATWG.
- Using shadow DOM: encapsulation from CSS, MDN.
- Eschewing Shadow DOM, Heydon Pickering, Every Layout.
- Pros and cons of using Shadow DOM and style encapsulation, Manuel Matuzović.
- Presentational shadow DOM, Mayank.
- Shadow DOM, templates, and slots, Chrome for Developers.
- Author-defined CSS names and the shadow DOM, Chrome for Developers.
- CSS Shadow Module Level 1: Name-Defining Constructs and Inheritance, W3C CSS Working Group.
- Attribute reflection: Reflected element reference scope, MDN.
- Chrome 152 release notes: Reference Target for cross-root ARIA, Chrome for Developers.
- Light DOM, Lightning Web Components docs.
- Declarative Shadow DOM, web.dev.
- Style scoping versus shadow DOM: which is fastest?, Nolan Lawson.
- Working with Shadow DOM: Implementing createRenderRoot, Lit.
- DOM Standard: find slottables, WHATWG.
- @scope, MDN.
- <slot>: The Web Component Slot element, MDN.
- Shadow DOM is for hiding your shame, Theresa O'Connor.
Coming next: Scoped custom element registries. Two libraries both want the name my-button. How can each shadow root keep its own list of tags?