Styles inside a shadow root
Learn how to add CSS to shadow DOM with a style or link element, which properties a shadow root inherits from the page, and how to reset them.
- 01Put styles inside a shadow rootUse a
<style>or a<link rel="stylesheet">in a shadow root, and know why a link can show the card plain for a moment. - 02Say what crosses the boundaryTell inherited properties like
colorandfont-family, which pass in from the page, from ones likeborder, which don't. - 03Reset what comes inStart fresh with
all: initial, give inner buttons the page's font withfont: inherit, and keep selectors short.
How do you add CSS to shadow DOM?
It's a quiet morning at Leaf and Kettle. Asha is giving the menu page a new look. She sets the page's font to Georgia. She makes every tea name crimson, with a .name rule. Then she reloads.
The tea cards change, but only halfway. Their text is in Georgia now. But each card's tea name stays sea green, not crimson. And the card's Add button keeps its small, plain font. Some of Asha's styles reached into the card. Others didn't. Why?
A shadow root carries its own CSS, in a <style> or <link rel="stylesheet"> element inside it. Those rules only match elements in that root. The page's rules only match the page. What does cross is inherited values, like color and font-family. They flow from the page into the component, unless the component resets them.
Here is Asha's page, cut down to one card:
<style> body { font-family: Georgia, serif; } .name { color: crimson; }</style><p class="name">Today's teas</p><tea-card></tea-card><script src="tea-card.js"></script><script> const inside = document.querySelector("tea-card").shadowRoot; for (const name of [document.querySelector(".name"), inside.querySelector(".name")]) { const style = getComputedStyle(name); console.log(name.textContent, style.color, style.fontFamily); }</script>- Lines 2 and 3 are Asha's page rules. One sets a font for the whole page. The other makes anything with the class
namecrimson. - Line 5 is a page paragraph with that class. Line 6 is the card.
- In the
tea-card.jstab, lines 6 to 8 put a<style>element inside the card's shadow root. Its rule, on line 7, makes.namesea green. Line 9 is the card's own.nameparagraph. - Back in the page, lines 10 to 13 read both names with
getComputedStyle(). It gives an element's final styles, after every rule is applied. Styles and classes covers it.
It prints Today's teas rgb(220, 20, 60) Georgia, serif, then Green tea rgb(46, 139, 87) Georgia, serif. The page's name is crimson. The card's name is sea green. But both are in Georgia.
So two things happened at once. The page's .name rule never matched the card's paragraph. Selectors stay in their own tree. But the font got in anyway. Asha never selected the card's paragraph. She set a font on body, and the paragraph inherited it.
font-family is inherited. The page's .name rule stops at the edge. Inside, only the card's own .name rule matches Green tea.Leaf and Kettle keeps its best cups on a shelf behind the front window. Sunlight and the warmth of the street pass through the glass, and the cups catch the light. But a customer can't reach through the glass to move a cup. Only the staff inside arrange the shelf.
- In real life: Sunlight and warmth through the glass
- In JavaScript: Inherited values, like
colorandfont-family - In real life: A customer's hand
- In JavaScript: A page selector, like
.name - In real life: The shelf behind the glass
- In JavaScript: The card's shadow root
- In real life: The staff who arrange the cups
- In JavaScript: The root's own
<style>rules
Put a component's CSS inside its shadow root, in a <style> or a <link rel="stylesheet">. Its rules style only that root, and the page's rules style only the page. Inherited values, like the text color and the font, still flow in from the page, unless the component resets them.
Lesson 6.3 showed this boundary with a single rule. This lesson teaches you to work with it: the two ways to ship styles, what inherits, how to reset it, and why short selectors are safe.
How do you use a style or link element in shadow DOM?
A shadow root can hold the same two style elements a page uses:
- a
<style>element, with the CSS written inside it; - a
<link rel="stylesheet">element, which loads the CSS from a file.
Both style only the root they sit in. The CSS Shadow spec says a style sheet "embedded in or linked from" an element in a shadow tree is matched against that tree. MDN adds the other half: a shadow root's styles don't affect the rest of the page.
A style element in every root
Lesson 6.1's tea card put a <style> in an innerHTML string. Lesson 7.1 moved the same markup into a template, made once at the top of the module and cloned into each card. The <style> goes along with each clone. So does every card carry its own copy of the CSS? Ask the browser:
<style> body { font-family: Georgia, serif; }</style><tea-card></tea-card><tea-card></tea-card><script src="tea-card.js"></script><script> const [first, second] = document.querySelectorAll("tea-card"); console.log("Page:", document.styleSheets.length); console.log("First card:", first.shadowRoot.styleSheets.length); console.log("Same sheet?", first.shadowRoot.styleSheets[0] === second.shadowRoot.styleSheets[0]);</script>- In the
tea-card.jstab, lines 1 to 6 make one template with a<style>and a paragraph. Line 12 clones it into each card's shadow root. - The page uses two cards, on lines 4 and 5.
- Line 9 counts the page's style sheets.
document.styleSheetslists the sheets in the page's own tree. - Line 10 counts the first card's. A shadow root has a list of its own,
shadowRoot.styleSheets. - Line 11 asks whether the two cards share one sheet object.
It prints Page: 1, First card: 1, and Same sheet? false. The page's list holds only its own <style>. Each card's root lists one sheet, and each card has its own.
That sounds wasteful, but MDN explains why it isn't. Many browsers notice <style> elements cloned from one node, or with the same text. They share one parsed sheet behind them. So one <style> per root is fine. Lesson 11.5, Constructable stylesheets, shares one sheet object on purpose.
A link to a stylesheet file
The second way keeps the CSS in a file of its own. A <link rel="stylesheet"> inside the shadow root loads it:
<template id="card-template"> <link rel="stylesheet" href="tea-card.css"> <p class="name">Green tea</p></template><tea-card></tea-card><script src="tea-card.js"></script>- Lines 1 to 4 are a template in the page, as in lesson 7.1. Line 2 is the link. Line 3 is the card's name.
- The
tea-card.csstab holds the rule: sea green and bold. - In the
tea-card.jstab, line 1 finds the template once. Line 7 clones it into each card's shadow root.
The result shows Green tea in bold sea green. Lesson 7.1 said a template's stylesheets don't load: its content is asleep. The copy in the shadow root is awake, so the browser loads tea-card.css then. The sheet belongs to the root the link sits in, so it styles only the card.
Does the browser download the file once for every card? The course tried three cards that link the same file. Chrome asked the server for it once, and all three cards used it.
Where does a link find its file?
A component can also make its link in JavaScript, as MDN's example does. Then the address needs care. The HTML Standard says a link's address is read against the page's address, not the script's. So link.href = "tea-card.css", set in tea-kit/tea-card.js, asks for the file next to the page, not the one inside tea-kit. Build the address from the module's own address instead:
const link = document.createElement("link");
link.rel = "stylesheet";
link.href = new URL("tea-card.css", import.meta.url);
this.shadowRoot.append(link);- Lines 1 and 2 make a link element for a stylesheet.
- Line 3 sets its address.
import.meta.urlis the address of the module file itself, andnew URL()readstea-card.cssagainst it. The file is found next totea-card.js, wherever the kit is served. - Line 4 puts the link in the shadow root.
These lines belong inside a component's constructor, in a module file. On their own they can't run, so they have no result.
Does a link make the card wait?
A <style> is ready the moment it's in the root. A <link> has to fetch its file first. And the browser doesn't wait for it.
The HTML Standard explains why. A page can hold back its first paint for style sheets, but only for ones added before its <body> exists. A link in the page's <head> is one of those. A component adds its link later, so it never holds anything back. Until the file arrives, the card is drawn without its styles. MDN calls this a flash of unstyled content.
<style> is ready at once. A <link> doesn't make the browser wait, so on a slow connection the first paint can show the card plain, then styled once the file arrives.On a fast connection you may never see it. The course held back tea-card.css on purpose. Chrome kept drawing frames while it waited, with the card plain, and styled it the moment the file arrived. Why it matters: a <style> never flashes. A <link> keeps your CSS in a real .css file, but the first paint may show the card plain.
In the kitchen at Leaf and Kettle, some tea jars have the recipe taped to the jar. Pick one up and you can start. Other jars only say "see page 12 of the recipe book". Someone has to fetch the book first. If a customer is waiting, the first cup may be made without it.
- In real life: The recipe taped to the jar
- In JavaScript: A
<style>inside the shadow root - In real life: A note: "see page 12 of the recipe book"
- In JavaScript:
<link rel="stylesheet" href="tea-card.css"> - In real life: Fetching the book from the shelf
- In JavaScript: The browser loading the file
- In real life: A cup made before the book arrives
- In JavaScript: The card drawn before its styles load
- In real life: One book for every jar
- In JavaScript: One file, fetched once, for every card
Which CSS properties are inherited into shadow DOM?
Asha's font got into the card without selecting anything. That's inheritance. When an element has no value of its own for certain properties, it takes its parent's value. Only some properties work this way. The CSS specs mark each one as inherited or not.
Lesson 6.3 showed a color passing into a card. Here is one page rule with two properties, one of each kind:
<style> tea-card { color: saddlebrown; border: 2px solid crimson; }</style><tea-card></tea-card><script src="tea-card.js"></script><script> const name = document.querySelector("tea-card").shadowRoot.querySelector("p"); const style = getComputedStyle(name); console.log("color:", style.color); console.log("border:", style.borderTopWidth);</script>- Line 2 is the page's rule for the card: a saddlebrown color and a crimson border.
- The
tea-card.jstab gives the card a shadow root with one paragraph, Green tea, and no styles. - Line 7 finds that paragraph. Line 8 gets its final styles.
- Line 9 prints its color. Line 10 prints the width of its top border.
It prints color: rgb(139, 69, 19) and border: 0px. The paragraph is saddlebrown, like the card. But it has no border. In the result, the crimson border is drawn once, around the whole card.
color is inherited, so the name inside gets saddlebrown too. border isn't, so the name's border is 0px.Why does the paragraph inherit from the card? In the DOM, the card isn't its parent: the paragraph lives in the card's shadow tree. The CSS Cascade spec says inheritance follows the flattened element tree instead. That's the tree the browser draws, where a shadow root's contents take the place of the host's children. In that tree, the paragraph's parent is the card. Lesson 8.2 showed the same tree carrying a color through a slot.
Now test the other properties yourself. Pick one for the page's rule:
<style> tea-card { color: saddlebrown; }</style><tea-card></tea-card><script src="tea-card.js"></script><script> const card = document.querySelector("tea-card"); const name = card.shadowRoot.querySelector("p"); console.log("Card:", getComputedStyle(card).color); console.log("Name:", getComputedStyle(name).color);</script>color is inherited. The name has no color of its own, so it takes the card's: saddlebrown.
- These cross:
color,font-family,line-height,text-align, andcursor. So dofont-size,letter-spacing, andvisibility. - These stop:
background-color,border, andpadding. Each one belongs to a single box.
Look closely at background-color. The name's own background prints rgba(0, 0, 0, 0), which is transparent. Yet the result shows wheat behind it. Nothing was inherited. The card's box is painted wheat, and the see-through name lets it show.
Children grow up speaking the language of their home. Nobody hands each child a copy: they pick it up from the people around them. But they don't inherit the walls or the paint. Those belong to the house alone.
- In real life: The home
- In JavaScript: The card, the shadow host
- In real life: The children
- In JavaScript: The elements inside its shadow root
- In real life: The language they pick up
- In JavaScript: Inherited properties:
color,font-family,line-height - In real life: The walls and the paint
- In JavaScript:
border,background-color,padding: one box's own properties
Why it matters: inheritance is why components fit their page with no work. The card's text matches the page's text. It's also why a page can change a component's look without asking. The next section shows how to stop it.
Custom properties, like --tea-accent, inherit too. Lesson 2.3 used them, and lesson 12.1 turns them into a styling API.
How do you reset inherited styles in shadow DOM?
Sometimes a component needs a clean start. Say it must look the same on every page that uses it, whatever font or color the page picked. web.dev's shadow DOM guide suggests one line for this: all: initial on the host.
all is a shorthand for every CSS property at once. It only takes the keywords every property accepts, like initial. And initial means the property's starting value, the one the CSS spec gives it before any style sheet or parent changes it.
<style> body { font: italic 20px Georgia, serif; color: saddlebrown; }</style><tea-card></tea-card><script src="tea-card.js"></script><script> const card = document.querySelector("tea-card"); const style = getComputedStyle(card.shadowRoot.querySelector("p")); console.log("Name:", style.color, style.fontSize, style.fontStyle); console.log("Card:", getComputedStyle(card).display);</script>- Line 2 gives the page an italic 20px Georgia font, in saddlebrown.
- In the
tea-card.jstab, line 7 is the reset.:hostselects the card itself, from inside its shadow root. The next lesson covers it in full.all: initialresets every property on the card. Thendisplay: blocksets one back, because a custom element isinlineby default. - Line 8 gives the name a white background. The reset also drops the page's light or dark setting, so the text is black. White keeps it readable in any theme.
- Back in the page, line 9 prints the name's color, size, and style. Line 10 prints the card's
display.
It prints Name: rgb(0, 0, 0) 16px normal and Card: block. Black, 16px, and upright: the starting values. The card got them first, and the name inherited them. Nothing from the page got through.
A new barista arrives at Leaf and Kettle in their own clothes. Before the shift, they change into the plain shop uniform. Then they pin on the name badge. Whatever they wore on the street, every barista starts the shift looking the same.
- In real life: The clothes they arrived in
- In JavaScript: The values the card would inherit from the page
- In real life: Changing into the plain uniform
- In JavaScript:
all: initial - In real life: Pinning on the badge afterwards
- In JavaScript: The declarations after
all, likedisplay: block
The badge goes on after the uniform. CSS works the same way: inside one rule, a later declaration beats an earlier one. So write all first. Try the other order, and four other resets, here:
<style> body { font: italic 20px Georgia, serif; color: saddlebrown; }</style><tea-card></tea-card><script src="tea-card.js"></script><script> const card = document.querySelector("tea-card"); const style = getComputedStyle(card.shadowRoot.querySelector("p")); console.log("Name:", style.color, style.fontSize, style.fontStyle); console.log("Card:", getComputedStyle(card).display);</script>Name: rgb(0, 0, 0) 16px normal. Card: block. all: initial resets every property on the card to its starting value. The name inherits those, so nothing from the page gets through. Then display: block sets one property back.
- No reset: the name takes the page's color, size, and italic style.
- font: initial resets only the font. The name is 16px and upright, but still saddlebrown.
- all: initial resets everything, as before.
- all: revert looks like a reset, but the page's styles still come in.
- display before all:
all: initialcomes second, so it resetsdisplaytoo. The card printsinline.
Why does all: revert keep the page's styles? The spec says revert acts as if your own rules for that property weren't there. Then the browser's own styles apply. The browser has no color or font rule for a custom element, so the card inherits them, just as before. Read the table across to compare the four keywords:
| When you write | For an inherited property, like color | For other properties, like border |
|---|---|---|
initial | The property's starting value. The page's value is dropped. | The property's starting value. |
inherit | The parent's value, which is what happens anyway. | The parent's value, even though it normally isn't passed down. |
unset | The parent's value, as if you wrote inherit. | The starting value, as if you wrote initial. |
revert | The browser's own style, if it has one. Otherwise the parent's value. | The browser's own style, if it has one. Otherwise the starting value. |
What does the all property leave alone?
all skips a few things on purpose. The CSS Cascade spec says it resets every property except direction and unicode-bidi, and never touches custom properties. This page puts the reset card in a right-to-left block, with a custom property on the page:
<style> body { color: saddlebrown; font-size: 20px; --tea-accent: crimson; }</style><div dir="rtl"> <tea-card></tea-card></div><script src="tea-card.js"></script><script> const name = document.querySelector("tea-card").shadowRoot.querySelector("p"); const style = getComputedStyle(name); console.log("Reset:", style.color, style.fontSize); console.log("Kept:", style.getPropertyValue("--tea-accent"), style.direction);</script>- Line 2 sets a color, a size, and a custom property,
--tea-accent, on the page. - Lines 4 to 6 put the card in a
<div dir="rtl">. That's a right-to-left block, as for Arabic or Hebrew. - The
tea-card.jstab is the reset card from before. - Line 11 prints the name's color and size. Line 12 prints
--tea-accentand the direction.
It prints Reset: rgb(0, 0, 0) 16px and Kept: crimson rtl. The color and size were reset. The custom property and the direction came through.
all: initial on the card, the page's color and size stop at the card. A custom property and the direction still come through: all never resets them.Both gaps are on purpose. The spec says direction belongs in the markup, with the dir attribute, not in a style sheet. And custom properties are how a page can still talk to a reset component. color: var(--tea-accent) inside the card would still pick up crimson. Lesson 12.1 builds on that.
Where should the reset go?
A reset on :host has one weak spot. A page rule written for tea-card itself beats a :host rule. Lesson 11.4 explains that order. So if the page says tea-card { color: darkorange; }, the name turns dark orange, reset or not. A reset on an element inside the root has no such problem:
<style> body { color: saddlebrown; } tea-card { color: darkorange; }</style><tea-card><span slot="note">Fresh today</span></tea-card><script src="tea-card.js"></script><script> const card = document.querySelector("tea-card"); const name = card.shadowRoot.querySelector("p"); const note = card.querySelector("span"); for (const element of [card, name, note]) { console.log(element.localName, getComputedStyle(element).color); }</script>- Line 3 gives the card itself a dark orange color.
- Line 5 slots a note from the page, Fresh today, into the card.
- In the
tea-card.jstab, line 7 resets a wrapper,<article class="card">, instead of the host. Lines 9 to 12 put the name and the note's slot inside it. - Lines 11 to 13 of the page print the color of the card, the name, and the note.
It prints tea-card rgb(255, 140, 0), then p rgb(0, 0, 0) and span rgb(0, 0, 0). The card itself is dark orange: the page's rule styles it. But inside, the wrapper started fresh. With the same reset on :host instead, all three lines print dark orange.
Look at the note. It's the page's own <span>, a child of the dark orange card. Yet it's black. In the flat tree, a slotted element inherits from its slot, and this slot sits inside the reset wrapper. Why it matters: a reset inside the root covers slotted content too.
Why doesn't a button in shadow DOM use the page font?
Back to Asha's Add button. Buttons, inputs, and other form controls don't inherit their font. The browser's own style sheet gives them a small control font. Chrome's styling guide calls this "the single most common miss" for components that wrap a native control.
A page can fix its own buttons with a reset like button { font: inherit; }. But as lesson 6.4 showed, a page reset can't reach inside a shadow root. So the component needs the line itself:
<style> body { font: 20px Georgia, serif; }</style><tea-card></tea-card><script src="tea-card.js"></script><script> const add = document.querySelector("tea-card").shadowRoot.querySelector("button"); console.log(add.textContent, getComputedStyle(add).fontSize);</script>- Line 2 gives the page a 20px Georgia font.
- In the
tea-card.jstab, line 7 is the fix: the card's buttons inherit the font. Line 10 is the Add button. - Line 8 of the page prints the button's text and font size.
It prints Add 20px. Now delete line 7 in the tea-card.js tab. It prints Add 13.3333px, the browser's size for form controls. font: inherit takes the whole font from the parent: the family, the size, and the line height. A button's text color doesn't inherit either, so add color: inherit when you want that too.
Why can CSS selectors stay simple in shadow DOM?
On a big site, many people's CSS ends up on one page. Two teams both write .name, and one team's rule changes the other's headings. One fix is a long prefix on every class. BEM, a naming method, writes names like .tea-card__name. Monica Dinculescu points out that naming methods like this grew up because CSS had no way to keep styles apart.
A shadow root is that way. Selectors are matched one tree at a time. This page and its card use the same class and the same id:
<style> .name { color: crimson; } #price { color: darkorange; }</style><p class="name">Today's teas</p><p id="price">Prices include tax</p><tea-card></tea-card><script src="tea-card.js"></script><script> const inside = document.querySelector("tea-card").shadowRoot; for (const p of [...document.querySelectorAll("p"), ...inside.querySelectorAll("p")]) { console.log(p.textContent, getComputedStyle(p).color); }</script>- Lines 2 and 3 are page rules for
.nameand#price. Lines 5 and 6 are the page's paragraphs. - In the
tea-card.jstab, lines 7 and 8 are the card's rules for the same.nameand#price. Lines 10 and 11 are its paragraphs. - Lines 11 to 13 of the page print the color of all four paragraphs.
It prints Today's teas rgb(220, 20, 60) and Prices include tax rgb(255, 140, 0): crimson and dark orange, from the page's rules. Then Green tea rgb(46, 139, 87) and Price: 4 rgb(70, 130, 180): sea green and steel blue, from the card's rules. No rule crossed, in either direction. Each tree even has its own #price, as lesson 6.3 showed for ids.
So inside a shadow root, short names are enough:
/* On a page that many people share */
.tea-card__name { color: seagreen; }
.tea-card__price--sale { color: crimson; }
/* Inside the tea card's shadow root */
.name { color: seagreen; }
.price.sale { color: crimson; }- Lines 2 and 3 are what a shared page needs: the component's name in every class.
- Lines 6 and 7 do the same job inside the card's shadow root.
web.dev's guide calls simpler selectors "a best practice inside Shadow DOM". Why it matters: short selectors are easier to read and to change, and no page can break them by accident.
In an office kitchen, everyone writes their name on their jars: "Asha's sugar", "Ravi's sugar". Otherwise somebody takes the wrong one. At home, a jar that says "sugar" is enough. Nobody else's jars are on your shelf.
- In real life: The shared office kitchen
- In JavaScript: One page where every team's CSS meets
- In real life: Names written on every jar
- In JavaScript: Long prefixed classes, like
.tea-card__name - In real life: Your own kitchen at home
- In JavaScript: The card's shadow root
- In real life: A jar that just says "sugar"
- In JavaScript: A short selector, like
.nameorbutton
Now sort each page rule. Does it reach inside the card, or stop at its shadow root?
body { color: saddlebrown; }body { font-family: Georgia, serif; }tea-card { line-height: 1.6; }body { --tea-accent: crimson; }.name { color: crimson; }p { margin: 0; }button { font: inherit; }* { box-sizing: border-box; }#price { color: darkorange; }
Drag each page rule to where it ends up: inside the card, or stopped at its shadow root.
What happened to /deep/, >>> and ::shadow?
Older guides style the inside of shadow roots from the page with /deep/, >>>, or ::shadow. /deep/ and ::shadow came from the first version of shadow DOM, and >>> was a later name for /deep/. All three are gone, as lesson 6.3 said. Chrome 63, in 2017, made /deep/ act like a plain space and ::shadow match nothing. Chrome removed the last of the early shadow DOM code in Chrome 89, in 2021. Today Chrome drops any CSS rule that uses them, and querySelector() throws a SyntaxError.
The CSS Shadow spec explains the choice: >>> showed too much of a component's inside. A page now has three ways in, each with its own lesson: inherited values, custom properties (lesson 12.1), and parts a component names itself (lesson 12.2).
Giving the tea card's buttons the page font
Asha's last problem is in the kit itself. The card's Add button sits in its shadow root. So do the - and + buttons of the quantity part from lesson 9.2. Asha's page already has button { font: inherit; }. It fixes her own buttons, but not the kit's.
This lesson's kit adds one line to the end of each component's <style>: button { font: inherit; } in tea-card.js, and the same in tea-quantity.js. Switch between the two kits:
<style> body { font: 20px Georgia, serif; } button { font: inherit; }</style><button>Ask Ravi</button><tea-card name="Green tea" price="4"></tea-card><script type="module"> import "./tea-kit/index.js"; const add = document.querySelector("tea-card").shadowRoot.getElementById("add"); for (const button of [document.querySelector("button"), add]) { console.log(button.textContent, getComputedStyle(button).fontSize); }</script>Ask Ravi 20px. Add 1 13.3333px. The page's button { font: inherit; } gives Ask Ravi the page font. The card's Add button keeps the browser's small control font, 13.3333px.
- Line 2 is Asha's 20px Georgia font. Line 3 is her button reset.
- Line 5 is a page button. Line 6 is a kit card.
- Line 8 loads the kit. Line 10 finds the card's Add button.
- Lines 11 to 13 print each button's text and font size.
With the kit from lesson 10.2, it prints Ask Ravi 20px and Add 1 13.3333px. With this lesson's kit, both print 20px, and Add matches Ask Ravi. The - and + buttons change too: look at the result.
Why only buttons? Everything else in the card is text, and text already inherits the page font. That's the habit to keep: let a component's text inherit, and give each form control inside it font: inherit.
Common mix-ups
- "Page CSS never reaches a component." No. Page selectors stop at a shadow root. But inherited values, like
colorandfont-family, and custom properties flow in. - "Backgrounds are inherited, because the page's background shows behind the card." No.
background-colorisn't inherited. The inner elements are transparent, so what's behind them shows through. - "
all: revertis a strongerall: initial." No.revertfalls back to the browser's own styles, and inherited properties keep coming from the page. - "
all: initialresets everything." No. It never resets custom properties,direction, orunicode-bidi. - "A link in a shadow root waits for its file, like one in the head." No. It doesn't hold back the paint, so the card can show plain until the file arrives.
- "A relative
hrefin a component's link is read against the component's file." No. It's read against the page's address. Usenew URL("tea-card.css", import.meta.url). - "
/deep/and>>>still reach into shadow roots." No. Chrome drops rules that use them, andquerySelector()throws aSyntaxError.
Practice exercises
Answer first, then use the hints. The pages run live, so you can check yourself.
The page gives the card a color and a padding. What does the console print for the name inside the card?
<style> tea-card { color: saddlebrown; padding: 8px; }</style><tea-card></tea-card><script src="tea-card.js"></script><script> const name = document.querySelector("tea-card").shadowRoot.querySelector("p"); const style = getComputedStyle(name); console.log(style.color, style.paddingTop);</script>rgb(139, 69, 19) 0px. color is inherited, so the name takes the card's saddlebrown. padding isn't, so the name's padding is 0px, while the card has 8px around everything.
The style sheet has three rules. How many does the browser keep?
<style> tea-card /deep/ p { color: crimson; } tea-card::shadow p { color: crimson; } p { color: saddlebrown; }</style><script> console.log(document.querySelector("style").sheet.cssRules.length);</script>1. Chrome can't read /deep/ or ::shadow, so it drops both rules when it reads the sheet. Only p { color: saddlebrown; } is left.
The card's note box ignores the page's 20px Georgia font. Fix it in the tea-card.js tab. What does your fixed page print?
<style> body { font: 20px Georgia, serif; }</style><tea-card></tea-card><script src="tea-card.js"></script><script> const box = document.querySelector("tea-card").shadowRoot.querySelector("input"); console.log(getComputedStyle(box).fontSize);</script><style> body { font: 20px Georgia, serif; }</style><tea-card></tea-card><script src="tea-card.js"></script><script> const box = document.querySelector("tea-card").shadowRoot.querySelector("input"); console.log(getComputedStyle(box).fontSize);</script>In tea-card.js, the shadow root gets <style> input { font: inherit; } </style> before the label. The page now prints 20px instead of 13.3333px. The label's text already used the page font; only the input needed the line.
The card should be a block with a sea green border. It shows neither. What does the starter print? Then fix line 7 in the tea-card.js tab.
<p>Our teas</p><tea-card></tea-card><script src="tea-card.js"></script><script> console.log(getComputedStyle(document.querySelector("tea-card")).display);</script><p>Our teas</p><tea-card></tea-card><script src="tea-card.js"></script><script> console.log(getComputedStyle(document.querySelector("tea-card")).display);</script>The starter prints inline. all: initial comes last, so it resets the display and the border written before it. With :host { all: initial; display: block; border: 2px solid seagreen; }, the card is a block with its border, and the page prints block.
The card resets everything, yet its name is dark orange. Make the reset win without touching the page. What does your fixed page print?
<style> tea-card { color: darkorange; }</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).color);</script><style> tea-card { color: darkorange; }</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).color);</script>rgb(0, 0, 0). The page's rule still colors the card itself dark orange, but the page can't select the wrapper. .card { all: initial; } starts it fresh, and the name inherits black from the wrapper.
Keep the card looking the same, but load its CSS from tea-card.css with a link instead of a <style>.
<template id="card-template"> <style> .name { color: seagreen; font-weight: bold; } </style> <p class="name">Green tea</p></template><tea-card></tea-card><script src="tea-card.js"></script><template id="card-template"> <link rel="stylesheet" href="tea-card.css"> <p class="name">Green tea</p></template><tea-card></tea-card><script src="tea-card.js"></script>The template now holds a link instead of a style. Each card's clone of it loads tea-card.css into its own shadow root, so the name is still bold sea green. On a slow connection, the card may show plain for a moment first.
Check your understanding
For each question, ask yourself: does a selector have to reach in, or does a value flow in by inheritance?
Question 1 of 7The page has
tea-card { color: saddlebrown; border: 2px solid crimson; }. What does a paragraph inside the card's shadow root get?Choose an answer to see the explanation.
Question 2 of 7Which page rule can change how the card's inner
.nameparagraph looks?Choose an answer to see the explanation.
Question 3 of 7What does this
all: revertcard print?Read the code, then predict<style> body { color: saddlebrown; } </style> <tea-card></tea-card> <script> const root = document.querySelector("tea-card").attachShadow({ mode: "open" }); root.innerHTML = "<style>:host { all: revert; }</style><p>Green tea</p>"; console.log(getComputedStyle(root.querySelector("p")).color); </script>Choose an answer to see the explanation.
Question 4 of 7A site's stylesheet has
button { font: inherit; }. Why does the Add button inside the tea card still use a small, plain font?Choose an answer to see the explanation.
Question 5 of 7The card's style has
:host { all: initial; display: block; }. What still comes in from the page?Choose an answer to see the explanation.
Question 6 of 7A component adds
<link rel="stylesheet" href="tea-card.css">to its shadow root. Does the browser wait for the file before it draws the card?Choose an answer to see the explanation.
Question 7 of 7Inside a shadow root, is
.namea safe class name?Choose an answer to see the explanation.
Key takeaways
- Put a component's CSS in its shadow root: a
<style>, or a<link rel="stylesheet">to a file.shadowRoot.styleSheetslists them. - Rules in a shadow root match only that root, and page rules match only the page. Short selectors are safe.
- A link in a shadow root doesn't hold back the paint, and a relative
hrefis read against the page's address. - Inherited properties, like
color,font-family, andline-height, flow in along the flat tree.border,background-color, andpaddingdon't. all: initialstarts fresh, but keeps custom properties and the direction. Write it first.all: revertdoesn't stop inheritance.- Buttons and inputs don't inherit the font. Give them
font: inheritinside the component.
Remember the one-liner.
A shadow root brings its own CSS and keeps it to itself. Only inherited values cross, and all: initial stops even those.
Sources
The facts on this page come from these standards, docs, and posts:
- Using shadow DOM: Applying styles inside the shadow DOM, MDN.
- Using custom elements: Referencing external styles, MDN.
- ShadowRoot: styleSheets property, MDN.
- HTML Standard: Link type "stylesheet", WHATWG.
- HTML Standard: Render-blocking mechanism, WHATWG.
- CSS Cascading and Inheritance Level 5: Inheritance, CSS Working Group.
- CSS Cascading and Inheritance Level 5: The all property, CSS Working Group.
- CSS Cascading and Inheritance Level 5: The revert keyword, CSS Working Group.
- CSS Shadow Module Level 1: Matching selectors against shadow trees, CSS Working Group.
- CSS Shadow Module Level 1: Flattening the DOM, CSS Working Group.
- Styling web components, Chrome for Developers.
- Shadow DOM v1: Self-contained web components, Eric Bidelman, web.dev.
- Shadow DOM: fast and encapsulated styles, Monica Dinculescu.
- Removing ::shadow and /deep/ in Chrome 63, Chrome for Developers.
- Shadow-piercing descendant combinator, /deep/, Chrome Platform Status.
Coming next: Styling the host. It styles the card itself with :host, the selector this lesson's resets used, and reacts to its attributes with :host().