Page styles for components
Learn how to style light DOM web components from the page: display and layout for each tag, room for undefined tags, @scope limits, and cascade layers.
- 01Style every tag from the pageGive each tag a display and a place in the layout, share tokens on
:root, and keep room for a tag that isn't defined yet. - 02Scope light DOM stylesStyle a light DOM component by its tag name or with
@scope, stop a scope withto, and know that neither reaches a shadow root. - 03Avoid conflictsPrefix tags and class names, and put a library's styles in a cascade layer, so the page's rules win.
How does page CSS style web components?
Meena is giving Leaf and Kettle's site a new look. She writes one rule for every button on the page: brown, with white text. Then she reloads the tea page. The Search button in the tea filter turns brown. The Add button on the tea card doesn't change at all.
Both come from Ravi's tea kit. Both are buttons. Why does her rule reach one and not the other? And what else should her page's CSS do for the kit's components?
Page CSS still styles every web component from the outside: its display, its place in the layout, and its look before it's defined. A light DOM component has no shadow root, so page CSS also reaches every element inside it. Keep those rules to the component with its tag name or @scope, and put a library's own rules in a cascade layer, so the page can win.
Here is Meena's problem in a few lines:
<style> tea-filter, tea-card { display: block; margin: 8px 0; padding: 4px; border: 2px solid seagreen; } button { font: inherit; background: saddlebrown; color: white; }</style><tea-filter><button>Search</button></tea-filter><tea-card></tea-card> <script src="tea-card.js"></script><script> customElements.define("tea-filter", class extends HTMLElement {}); const search = document.querySelector("tea-filter button"); const add = document.querySelector("tea-card").shadowRoot.querySelector("button"); console.log("Search:", getComputedStyle(search).fontSize); console.log("Add:", getComputedStyle(add).fontSize);</script>- Line 2 styles both tags: a block, with a sea green border. Line 3 styles every button.
font: inheritmakes a button use the page's font, like the text around it. - Line 5 is a filter with a button inside it. Line 10 defines
tea-filterwith an empty class, so it has no shadow root. - Line 6 is a card. In the
tea-card.jstab, its button sits in its shadow root. - Lines 11 to 14 find both buttons and print their font sizes.
It prints Search: 16px and Add: 13.3333px. Both tags got the border. Search got the brown and the page's 16px font. Add kept the browser's own small button font, as lesson 11.1 showed.
tea-filter, which has no shadow root, they also reach the button. Inside tea-card, they stop at the shadow root.The difference is where each button lives. A light DOM component keeps its insides among its own children, in the page's tree. Lesson 6.4 built them, and lesson 5.6 wrapped the page's own HTML in one. Page rules reach everything in that tree. A shadow root is a tree of its own, and page selectors stop at its edge.
Leaf and Kettle has a stall in a food hall. The hall manager decides where each stall stands and how much floor it gets. Some stalls are open counters, and the hall's lamps hang over them. Others are booths with walls. Inside a booth, the stall owner picks the lamps.
- In real life: The hall manager
- In CSS: The page's CSS
- In real life: Where each stall stands, and how much floor it gets
- In CSS:
displayand layout rules on each tag - In real life: A stall that is an open counter
- In CSS: A light DOM component, like
tea-filter - In real life: The hall's lamps over every open counter
- In CSS:
button { … }reaching the filter's button - In real life: A booth with its own walls
- In CSS: A shadow DOM component, like
tea-card
The page styles every tag from outside, and everything inside a light DOM component. Give each tag a display and a place. Keep rules for a light DOM component inside it, with its tag name or @scope. Put a library's rules in a layer, so the page's rules win.
What should a page stylesheet say about web components?
Most sites have a main style sheet. Its rules reach the whole document, from the root down. Here are the jobs it has for components, whether they use shadow DOM or not.
Give every tag a display
The browser has no style rule for your tag. So a custom element is display: inline, as Chrome's styling guide notes. An inline box ignores width and height. Lesson 11.2 fixed this inside a shadow root, with :host { display: block; }. A light DOM component has no :host:
<style> tea-menu { width: 240px; border: 2px solid seagreen; }</style><tea-menu>Green tea, Oolong</tea-menu> <script> customElements.define("tea-menu", class extends HTMLElement {}); const menu = document.querySelector("tea-menu"); console.log("Display:", getComputedStyle(menu).display); console.log("240px wide:", menu.getBoundingClientRect().width === 240);</script>- Line 2 asks for a 240px wide menu with a border.
- Line 7 defines the menu. Lines 9 and 10 print its display and check its width.
It prints Display: inline and 240px wide: false. Defining the tag didn't change its display. Only CSS does that, and for a light DOM component, the page's CSS is the only CSS it has. Burton Smith puts it plainly in his post on CSS-only custom elements: always declare the display you want. MDN's own :defined example writes custom-element { display: block; } in the page's CSS.
Place each tag with the page's layout
A tag is a box in the page's layout, like a <div>. So the page decides where it goes, how wide it is, and how much space sits around it. Here a shelf holds two shadow DOM cards and a light DOM menu:
<style> :root { --tea-gap: 16px; --tea-radius: 12px; } .shelf { display: grid; grid-template-columns: 1fr 1fr; gap: var(--tea-gap); width: 400px; } tea-menu { display: block; grid-column: 1 / -1; padding: 8px; border: 2px solid sienna; border-radius: var(--tea-radius); }</style><div class="shelf"> <tea-card>Green tea</tea-card> <tea-card>Oolong</tea-card> <tea-menu>Today: 2 teas</tea-menu></div> <script src="tea-card.js"></script><script> for (const box of document.querySelectorAll(".shelf > *")) { console.log(box.localName, box.getBoundingClientRect().width, getComputedStyle(box).borderTopLeftRadius); }</script>- Line 2 sets two tokens on
:root, the<html>element. A token is a named value the whole site shares, kept in a custom property. - Line 3 makes the shelf a grid: two equal columns, 16px apart, 400px wide in all.
- Line 4 gives the menu its display, and spans it across both columns with
grid-column: 1 / -1. It reads--tea-radiusfor its corners. - In the
tea-card.jstab, line 6 gives each card its own display, and reads the same--tea-radius, with 8px as its fallback. - Lines 14 to 16 print each box's name, width, and corner radius.
It prints tea-card 192 12px twice, then tea-menu 400 12px. Each card got half of 400px, less half the gap. Neither card knows about the grid. The page sized them, and the gap spaced them.
The radius came from one place. Custom properties are inherited, so the value on :root reached the menu, and crossed into each card's shadow root too. MDN calls :root the common place for values the whole document uses. Lesson 2.3 set Web Awesome's tokens there, and lesson 12.1 named the kit's own, like --tea-radius.
Before the tea fair, the organizer draws a floor plan. It marks each stand's spot, its width, and the aisles between stands. The stand makers build stands, not the floor. And every stand gets its trim painted from the same tin, so the hall looks like one shop.
- In real life: The floor plan
- In CSS: The page's grid,
.shelf - In real life: The spot and width marked for each stand
- In CSS: The grid columns and
grid-column - In real life: The aisle between stands
- In CSS:
gap: var(--tea-gap) - In real life: The one tin of paint every stand uses
- In CSS: A token on
:root, like--tea-radius
Why it matters: a component that fits any layout leaves its outside to the page. Every Layout's global and local styling describes the same split: each layout needs a container element that sets up the layout for its children. When a page rule and a component's :host rule set the same property on a tag, the page wins anyway, as lesson 11.4 showed.
Keep room for a tag that isn't defined yet
Tags show up before their script. Lesson 2.4 styled them while they wait, with :not(:defined). It hid them with a fallback, so they show anyway if the script never comes. It also kept their room, so nothing jumps when they upgrade.
A light DOM component can add markup of its own when it upgrades. The kit's tea-menu, from lesson 5.5, adds a summary line above its teas. That's one more line on the page, and the page's own CSS decides how tall it is. So the page can work out the room to keep:
<style> tea-menu, tea-item { display: block; line-height: 1.5rem; } tea-menu p { margin: 0; } tea-menu:not(:defined) { min-block-size: 6rem; }</style><tea-menu> <tea-item price="4">Green tea</tea-item> <tea-item price="5">Oolong</tea-item> <tea-item price="3">Mint</tea-item></tea-menu><p class="note">Prices are for one pot.</p> <script type="module"> const note = document.querySelector(".note"); const before = note.getBoundingClientRect().top; await new Promise((resolve) => setTimeout(resolve, 1000)); await import("./tea-kit/index.js"); const moved = note.getBoundingClientRect().top - before; console.log(`The note moved ${Math.round(moved)}px.`);</script>- Line 2 makes the menu and its teas blocks, each line 1.5rem tall. Line 3 takes the margins off the menu's summary.
- Line 4 keeps 6rem of height while the menu waits: one line for the summary, plus three teas.
- Line 11 is a note under the menu.
- Line 15 measures where the note's top edge is. Line 16 waits a second. Line 17 loads the kit, and the menu upgrades. Lines 18 and 19 measure again and print how far the note moved.
It prints The note moved 0px. Press Edit & run and delete line 4. Now it prints The note moved 24px.: one line, as the summary arrives.
Where these rules go matters as much as what they say:
- In the page's CSS. A rule for a tag that isn't defined yet must arrive before the component's script. Nothing in that script can style the tag before it runs.
- On the part that needs it. Lesson 2.4 warned against hiding the whole
body. One slow component would hold back the whole page. - With a fallback.
visibility: hiddenon its own hides the words for good if the script fails. Burton Smith lists that among the old fix's problems. Cory LaViska's own fix shows the page after two seconds at most.
Why use :not(:defined) at all, when the page styles the menu anyway? Because the reserve is only for the wait. Once the menu is defined, its real content decides its height, and a reader may add or filter teas.
How do you style light DOM web components from the page?
A light DOM component's insides are ordinary page elements. So you style them like any other part of the page. Hawk Ticehurst writes that such markup "can be styled like regular HTML". Two habits keep that safe.
Start each rule with the tag name
Page rules like p and button reach everywhere. That includes the markup a component adds:
<style> p { margin: 0 0 1.5rem; color: dimgray; } tea-menu { display: block; padding: 8px; border: 2px solid seagreen; } tea-item { display: block; } tea-menu > p { margin: 0; color: seagreen; font-weight: bold; }</style><p>Fresh teas every morning.</p><tea-menu> <tea-item price="4">Green tea</tea-item> <tea-item price="5">Oolong</tea-item></tea-menu> <script type="module"> import "./tea-kit/index.js"; const summary = document.querySelector("tea-menu > p"); console.log(summary.textContent); console.log("Color:", getComputedStyle(summary).color);</script>- Line 2 styles every paragraph on the page: dim gray, with a 1.5rem gap below.
- Lines 3 and 4 give the menu and its teas a display.
- Line 5 starts with the tag name:
tea-menu > pmatches only a paragraph right inside a menu. - Line 14 loads the kit. Line 15 finds the summary the menu added. Lines 16 and 17 print it and its color.
It prints 2 teas. Cheapest: Green tea, 4 and Color: rgb(46, 139, 87), sea green. Now press Edit & run and delete line 5. It prints Color: rgb(105, 105, 105), dim gray. The page's paragraph rule styled the menu's summary, and pushed the teas down too.
A tag name is a natural namespace: a name that keeps your rules apart from everyone else's. A custom element's name has a hyphen, so it never clashes with HTML's own tags. With lesson 3.1's prefix, tea-, it stays apart from other libraries too. tea-menu > p can't touch a paragraph anywhere else.
Keep selectors shallow
Lesson 11.4 scored selectors with three numbers, like 0-1-0. Compare two ways to style the summary:
/* Deep: tied to the markup, and hard to beat */
body main .shop tea-menu > p:first-child { color: seagreen; }
/* Shallow: the tag name, then one element */
tea-menu > p { color: seagreen; }- Line 2 walks down through five elements, then adds
:first-child. It scores0-2-4. To change the color later, a page needs a selector that scores at least as high. - Line 5 names the tag and one element, and scores
0-0-2. Any rule with a class beats it.
Deep selectors also tie your CSS to markup you may not own. Nolan Lawson tells the story of a page that styled a dropdown's inner class. A security update renamed the class and added a wrapper <div>, and the page's styles broke. Exercise 4 shows the same thing on a small scale. Every Layout draws the rule as an upside-down triangle: the more elements a rule reaches, the lower its specificity should be.
Here is how the page's rules reach each kind of component. Read each row across:
| What the page writes | A light DOM component, like tea-filter | A shadow DOM component, like tea-card |
|---|---|---|
tea-card { display: block; } on the tag | It styles the tag. | It styles the tag, and beats the card's own :host rule. |
button { … } for the whole page | It reaches every button inside. | It stops at the shadow root. |
:root { --tea-radius: 0; } | Page rules that read it get it. | It's inherited into the shadow root, so the card's own rules can read it. |
@scope (tea-card) { button { … } } | It styles the buttons inside the tag. | It stops at the shadow root. Only :scope, the tag itself, matches. |
tea-card::part(add) { … } | It isn't needed. The page can select the element. | It styles the part the card names. |
tea-card:not(:defined) { … } | It applies until the class arrives. | It applies until the class arrives. |
Why it matters: a light DOM component lives under your page's CSS, resets and all. Start its rules with its tag name, keep them short, and you can still win with one class when you need to.
How does CSS @scope style a light DOM component?
Lesson 6.4 met @scope: a CSS rule that limits other rules to one part of the page. @scope (tea-note) { … } kept a note's rules inside the note. Three more of its features help light DOM components:
:scopeinside the block styles the root itself.to (…)gives the scope a lower edge.- A scoped rule beats a plain one when they tie, because its root is closer.
Setting a lower edge with to
A filter wraps the page's own list. Ravi wants to style the filter's search form, but not buttons the page puts in its list. MDN calls a scope with an upper and a lower edge a donut scope. The upper edge is in the scope. The lower edge, and everything inside it, isn't. Move the edges:
<style> @scope (tea-filter) to (ul) { :scope { display: block; padding: 8px; border: 2px solid seagreen; } button { font-weight: bold; color: seagreen; } }</style><tea-filter> <form action="teas"> <input type="search" name="q" aria-label="Search teas"> <button>Search</button> </form> <ul> <li>Green tea <button>Add</button></li> <li>Oolong <button>Add</button></li> </ul></tea-filter> <script> for (const button of document.querySelectorAll("button")) { console.log(button.textContent, getComputedStyle(button).fontWeight); }</script>It prints Search 700, Add 400, Add 400. The scope stops at the <ul>. The list, and everything in it, is out of scope, so only Search is bold. The border still goes round tea-filter: the root is in its own scope.
- Line 2 is the only line that changes. It names the scope's root, and the limit after
to. - Line 3 uses
:scope: it puts a border round the root. Line 4 makes each button in scope bold and sea green. - Lines 19 to 21 print each button's font weight. 700 means bold, 400 means normal.
With to (ul), it prints Search 700, then Add 400 twice. The filter's own button is bold, and the page's list is left alone. to (form) turns that around. @scope (form) bolds the same button as to (ul), but the border moves to the form, because :scope follows the root.
tea-filter and includes it. It stops at the <ul>: the list and everything inside it are out.A painter is asked to paint the tea room, door frame included. One wall has a shelf that belongs to a tenant. The painter paints round it, and leaves the shelf, and everything on it, as it was.
- In real life: The tea room, from its door in
- In CSS: The root,
tea-filter, which is in scope - In real life: Painting the door frame too
- In CSS:
:scopestyling the root itself - In real life: The tenant's shelf
- In CSS: The limit,
to (ul) - In real life: Not painting the shelf or anything on it
- In CSS: The list and its buttons, out of scope
Why it matters: a light DOM component often holds content the page wrote. A limit keeps the component's rules off it. Burton Smith uses @scope (my-card) to ([slot]) in his CSS-only components for the same reason.
A style element inside the component
Lesson 6.4 mentioned one more form: @scope with no root, in a <style> inside the component. Its root is the <style>'s parent element. It can have a limit too:
<tea-filter> <style> @scope to (ul) { :scope { display: block; padding: 8px; border: 2px solid seagreen; } button { font-weight: bold; color: seagreen; } } </style> <form action="teas"> <input type="search" name="q" aria-label="Search teas"> <button>Search</button> </form> <ul> <li>Green tea <button>Add</button></li> </ul></tea-filter><button>Sign in</button> <script> for (const button of document.querySelectorAll("button")) { console.log(button.textContent, getComputedStyle(button).fontWeight); }</script>- Lines 2 to 7 are a
<style>insidetea-filter. Line 3 has no root, onlyto (ul). - Line 16 is a button outside the filter.
- Lines 19 to 21 print each button's font weight.
It prints Search 700, Add 400, and Sign in 400. The rules matched inside the filter, above its list, and nowhere else. The styles travel with the markup. A server template that writes the filter can write its <style> too.
Does @scope reach inside a shadow root?
No. A page's @scope is still page CSS. Try it on the card from the overview:
<style> @scope (tea-card) { :scope { display: block; border: 2px solid seagreen; } button { font-weight: bold; } }</style><tea-card></tea-card> <script src="tea-card.js"></script><script> const card = document.querySelector("tea-card"); const add = card.shadowRoot.querySelector("button"); console.log("Card border:", getComputedStyle(card).borderTopStyle); console.log("Add:", getComputedStyle(add).fontWeight);</script>- Line 2 scopes to
tea-card. Line 3 styles the tag with:scope. Line 4 tries to make buttons bold. - Lines 13 and 14 print the card's border style and the Add button's font weight.
It prints Card border: solid and Add: 400. The tag is in the page's tree, so :scope matched it. The Add button isn't. Adobe's tracker of CSS features for shadow DOM says the same: a page's @scope can't cross into a shadow tree. For a shadow DOM component, use the styling API the card offers: custom properties and parts.
When two scopes match, which one wins?
Scopes can sit inside each other. A menu can sit in a section of specials, each with its own scoped rule for paragraphs. When two rules tie on specificity, the browser then asks which root is closer. The spec calls this scope proximity: the fewest steps up from the element to its root. Try it:
<style> @scope (tea-menu) { p { color: seagreen; } } @scope (.specials) { p { color: sienna; } }</style><section class="specials"> <p>Today's specials</p> <tea-menu><p>3 teas</p></tea-menu></section> <script> for (const p of document.querySelectorAll("p")) { console.log(p.textContent, getComputedStyle(p).color); }</script>It prints Today's specials rgb(160, 82, 45) and 3 teas rgb(46, 139, 87). Both rules match 3 teas, and both are as specific. Its nearest root is tea-menu, one step up. .specials is two steps up. So 3 teas is sea green.
- Lines 2 and 3 are the only lines that change. Each colors paragraphs, one inside the menu, one inside the section.
- Line 6 is the section's own paragraph. Line 7 is the menu's.
- Lines 11 to 13 print each paragraph's color.
With both scopes, 3 teas is sea green in either order. Without @scope, .specials p wins on specificity, and 3 teas turns sienna. And with :scope p in the specials, it's sienna again: :scope counts like a class.
tea-menu root is one step up, and .specials is two. The nearer root wins.CSS Cascade 6 puts proximity after specificity and before the order of the rules. A rule with no scope counts as infinitely far away. So a scoped button rule beats a plain button rule from the page, even one that comes later. The conflicts section below meets that again.
At Leaf and Kettle, the shop manager says to put cups on the left. The counter supervisor says, for the counter, put them on the right. At the counter, the staff follow the supervisor, who is nearer. But an order with their own name on it beats both.
- In real life: The shop manager's instruction
- In CSS:
@scope (.specials) { p { … } } - In real life: The counter supervisor's instruction
- In CSS:
@scope (tea-menu) { p { … } } - In real life: The supervisor standing nearer
- In CSS: Fewer steps from the paragraph to its root
- In real life: A direct order with a name on it
- In CSS: A more specific selector, which wins first
@scope works in every current browser. It's Baseline newly available: Safari 26.4 was the last to add it in full.
How do you avoid style conflicts with light DOM components?
A light DOM component shares the page's cascade. Its rules and the page's rules meet on the same elements. Three habits keep them from fighting.
Prefix tag names and class names
Tag names already carry the kit's prefix, tea-. Class names inside a light DOM component need one too. A component that writes <p class="total"> picks up any .total rule the page has, and Exercise 5 shows it. Start each class with the tag's name:
/* The page's own rule, for its cart */
.total { font-size: 2rem; }
/* tea-order's own classes start with its tag name */
.tea-order__total { font-weight: bold; }
.tea-order__note { color: dimgray; }- Line 2 is the page's own rule, for its cart.
- Lines 5 and 6 are the component's classes. Each starts with
tea-order__, so the page's rule never matches them.
The two underscores come from BEM, short for Block Element Modifier. In BEM, a block is a stand-alone part, like tea-order. An element is a piece tied to it, like tea-order__total. MDN shows it as one common way to name classes.
Put a library's rules in a cascade layer
A kit ships its own CSS for its light DOM components. Its rules must look right on any page. They must also be easy to change. Lesson 11.4 showed the tool: a cascade layer, a named group of rules. Rules in no layer come after every layer, and layers are compared before specificity. Watch Meena's button rule against four versions of the kit's:
<style> /* The kit's CSS */ tea-filter button { background: seagreen; color: white; }</style><style> /* The page's CSS */ button { background: saddlebrown; color: white; }</style><button>Sign in</button><tea-filter><button>Search</button></tea-filter> <script> for (const button of document.querySelectorAll("button")) { console.log(button.textContent, getComputedStyle(button).backgroundColor); }</script>The Search line prints Search rgb(46, 139, 87). tea-filter button names two elements, and the page's button names one. The kit's rule is more specific, so Search stays sea green, though the page's rule comes later.
- Lines 1 to 4 stand in for the kit's file. Line 3 is the only line that changes.
- Line 7 is Meena's rule: brown buttons, in no layer.
- Lines 13 to 15 print each button's background.
As a plain rule, the kit's tea-filter button wins: it's more specific. In @scope, it wins too, by closeness. Put it in @layer tea-kit, and Meena's rule wins, however specific the kit's rule is.
A tea supplier gives Leaf and Kettle printed menus with its prices. The shop writes today's prices on a chalkboard by the door. When they differ, the chalkboard counts. Nobody compares how nice the printing is.
- In real life: The supplier's printed menu
- In CSS: The kit's rules, in
@layer tea-kit - In real life: The shop's chalkboard
- In CSS: The page's rules, in no layer
- In real life: The chalkboard wins
- In CSS: Unlayered rules beat layered ones
- In real life: However fancy the print
- In CSS: Whatever the kit's specificity
Why it matters: a library that layers its styles lets a page change them without longer selectors or !important. Layers come back in lesson 12.6, Organizing component CSS, which organizes a whole library's CSS.
Styling the tea kit's light DOM components
Before the kit changes, sort what the page's CSS reaches:
button { … }and the Search button insidetea-filterbutton { … }and the Add button intea-card's shadow roottea-card { display: block; }and thetea-cardtag@scope (tea-card) { button { … } }and the card's Add button@scope (tea-filter) to (ul) { button { … } }and a button in the filter's<ul>:root { --tea-radius: 0; }and the card's cornersp { … }and the summary paragraphtea-menuadds
Sort each pair: a page rule, and the element it might style.
The kit's tea-menu, tea-item, and tea-filter have no shadow root, so until now they had no styles at all. The kit gets a style sheet for them, tea-kit/light.css. A page links it before its own CSS:
/* The tea kit's styles for its light DOM components. Link it before the page's own CSS. */
@layer tea-kit {
tea-menu, tea-item, tea-filter { display: block; }
@scope (tea-menu) {
:scope > p { margin: 0 0 4px; font-weight: bold; }
}
@scope (tea-filter) to (ul) {
form { display: flex; gap: 8px; align-items: center; margin: 0 0 8px; }
input, button { font: inherit; padding: 4px 8px; border-radius: var(--tea-radius, 8px); }
button { border: 2px solid seagreen; background: white; color: seagreen; }
}
}- Line 2 puts everything in one layer,
tea-kit. Any page rule in no layer beats it. - Line 3 gives the three tags a display. The text-sized tags, like
tea-price, stay inline. - Line 6 makes the menu's own summary bold.
:scope > pmeans a paragraph right inside the menu. - Line 9 styles the filter down to its list, so the page's list stays the page's. Line 11 reads the kit-wide
--tea-radiusfor the corners.
Now one page uses both kinds of component, each styled its own way:
<link rel="stylesheet" href="tea-kit/light.css"><style> :root { --tea-radius: 0; } tea-filter button { background: seagreen; color: white; } tea-card { display: block; max-inline-size: 16rem; --tea-card-accent: sienna; } tea-card::part(add) { background: seagreen; color: white; }</style><tea-filter> <form action="teas"> <label>Search teas <input type="search" name="q"></label> <button>Search</button> </form> <ul> <li>Green tea</li> <li>Oolong</li> </ul></tea-filter><tea-card name="Green tea" price="4"></tea-card> <script type="module"> import "./tea-kit/index.js"; const search = document.querySelector("tea-filter button"); const root = document.querySelector("tea-card").shadowRoot; console.log("Search:", getComputedStyle(search).backgroundColor, getComputedStyle(search).borderTopLeftRadius); console.log("Add:", getComputedStyle(root.getElementById("add")).backgroundColor); console.log("Card corners:", getComputedStyle(root.querySelector(".card")).borderTopLeftRadius);</script>- Line 1 links the kit's light DOM styles, before the page's own.
- Line 3 squares every corner with one token on
:root. - Line 4 styles the filter's button with a plain page selector. It beats the kit's layered white button.
- Line 5 gives the card a display and a width, and sets its accent with lesson 12.1's
--tea-card-accent. Line 6 styles its Add button through theaddpart. - Lines 24 to 26 print what each button and the card got.
It prints Search: rgb(46, 139, 87) 0px, Add: rgb(46, 139, 87), and Card corners: 0px. Two strategies sit side by side. The filter's insides are page elements, so a page selector reaches them. The card's insides are private, so the page uses the API it offers. One token on :root reaches both.
Common mix-ups
- "Page CSS can't style web components." No. It styles every tag from outside, and everything inside a light DOM component. Only a shadow root's insides are out of reach.
- "Defining a tag makes it a block." No. A defined tag is still
display: inlineuntil some CSS gives it a display. - "
@scope (tea-card)reaches inside the card's shadow root." No. It matches the tag with:scope, and stops at the shadow root. - "
to (ul)styles everything down to the list, list included." No. The limit itself is out of scope, with everything inside it. - "A scoped rule always beats an unscoped one." No. Layers and specificity come first. Closeness only settles a tie.
- "A library should use strong selectors, so pages can't break its look." No. Put its rules in a layer. Then any page rule can change them.
- "Hide every tag with
:not(:defined) { visibility: hidden; }until it loads." No. With no fallback, the content stays hidden if the script fails. Keep the room, and hide only with a timeout.
Practice exercises
Answer first, then use the hints. The pages run live, so you can check yourself.
One rule turns buttons brown. The page counts the brown ones. What does it print?
<style> button { background: saddlebrown; color: white; }</style><button>Sign in</button><tea-filter><button>Search</button></tea-filter><tea-card></tea-card> <script src="tea-card.js"></script><script> customElements.define("tea-filter", class extends HTMLElement {}); const card = document.querySelector("tea-card"); const buttons = [...document.querySelectorAll("button"), ...card.shadowRoot.querySelectorAll("button")]; const brown = buttons.filter((button) => getComputedStyle(button).backgroundColor === "rgb(139, 69, 19)"); console.log("Brown buttons:", brown.length);</script>Brown buttons: 2. The page's rule reaches Sign in and Search, which are both in the page's tree. The Add button sits in the card's shadow root, where page selectors stop.
The scope runs from tea-filter down to each <li>. Which buttons are bold? Write what the page prints.
<style> @scope (tea-filter) to (li) { button { font-weight: bold; } }</style><tea-filter> <form action="teas"><button>Search</button></form> <ul> <li>Green tea <button>Add</button></li> </ul> <button>Clear</button></tea-filter> <script> const bold = [...document.querySelectorAll("button")].filter((button) => getComputedStyle(button).fontWeight === "700"); console.log("Bold:", bold.map((button) => button.textContent).join(", "));</script>Bold: Search, Clear. Both are inside tea-filter and outside every <li>. The limit cuts out each <li> and what's in it, so Add stays normal.
This page prints The note moved 24px. Add one rule so the note stays still. What does it print then?
<style> tea-menu, tea-item { display: block; line-height: 1.5rem; } tea-menu p { margin: 0; }</style><tea-menu> <tea-item price="4">Green tea</tea-item> <tea-item price="5">Oolong</tea-item> <tea-item price="3">Mint</tea-item></tea-menu><p class="note">Prices are for one pot.</p> <script type="module"> const note = document.querySelector(".note"); const before = note.getBoundingClientRect().top; await new Promise((resolve) => setTimeout(resolve, 1000)); await import("./tea-kit/index.js"); const moved = note.getBoundingClientRect().top - before; console.log(`The note moved ${Math.round(moved)}px.`);</script><style> tea-menu, tea-item { display: block; line-height: 1.5rem; } tea-menu p { margin: 0; } tea-menu:not(:defined) { min-block-size: 6rem; }</style><tea-menu> <tea-item price="4">Green tea</tea-item> <tea-item price="5">Oolong</tea-item> <tea-item price="3">Mint</tea-item></tea-menu><p class="note">Prices are for one pot.</p> <script type="module"> const note = document.querySelector(".note"); const before = note.getBoundingClientRect().top; await new Promise((resolve) => setTimeout(resolve, 1000)); await import("./tea-kit/index.js"); const moved = note.getBoundingClientRect().top - before; console.log(`The note moved ${Math.round(moved)}px.`);</script>The new line 4 keeps 6rem for the waiting menu, the height it has once its summary arrives. The note stays put, and the page prints The note moved 0px.
The Search button was sea green. Then the form's button got a wrapper, and the color is gone. Fix line 2. What does the page print then?
<style> tea-filter > form > button { background: seagreen; color: white; }</style><tea-filter> <form action="teas"> <input type="search" name="q" aria-label="Search teas"> <div class="actions"> <button>Search</button> </div> </form></tea-filter> <script> const search = document.querySelector("tea-filter button"); console.log("Search:", getComputedStyle(search).backgroundColor);</script><style> tea-filter button { background: seagreen; color: white; }</style><tea-filter> <form action="teas"> <input type="search" name="q" aria-label="Search teas"> <div class="actions"> <button>Search</button> </div> </form></tea-filter> <script> const search = document.querySelector("tea-filter button"); console.log("Search:", getComputedStyle(search).backgroundColor);</script>tea-filter > form > button only matched a button right inside the form. The new <div> broke that. tea-filter button matches any button inside the filter, so it prints Search: rgb(46, 139, 87).
The page's big crimson .total rule is meant for its cart. It also hits the order's total: Order total: 32px. Change the tea-order.js tab, not the page. What does the page print then?
<style> .total { font-size: 2rem; color: crimson; } tea-order { display: block; }</style><p class="total">Cart: 3 items</p><tea-order></tea-order> <script src="tea-order.js"></script><script> const total = document.querySelector("tea-order p"); console.log("Order total:", getComputedStyle(total).fontSize);</script><style> .total { font-size: 2rem; color: crimson; } tea-order { display: block; }</style><p class="total">Cart: 3 items</p><tea-order></tea-order> <script src="tea-order.js"></script><script> const total = document.querySelector("tea-order p"); console.log("Order total:", getComputedStyle(total).fontSize);</script>The page stays the same. In the tea-order.js tab, line 4 now gives the class tea-order__total, which the page's .total rule doesn't match. The order's total keeps the normal size: Order total: 16px.
The page wants brown buttons, but the kit's file keeps Search sea green. Change only the kit.css tab so the page wins. What does the page print then?
<link rel="stylesheet" href="kit.css"><style> button { background: saddlebrown; color: white; }</style><tea-filter><button>Search</button></tea-filter> <script> const search = document.querySelector("tea-filter button"); console.log("Search:", getComputedStyle(search).backgroundColor);</script><link rel="stylesheet" href="kit.css"><style> button { background: saddlebrown; color: white; }</style><tea-filter><button>Search</button></tea-filter> <script> const search = document.querySelector("tea-filter button"); console.log("Search:", getComputedStyle(search).backgroundColor);</script>The page stays the same. In the kit.css tab, the rule now sits in @layer tea-kit. Layers are compared before specificity, and the page's rule is in no layer, so it wins: Search: rgb(139, 69, 19).
Check your understanding
For each question, ask: is the element in the page's tree, and which step of the cascade decides?
Question 1 of 7A page writes
tea-menu { width: 240px; }for a light DOM menu, and the width does nothing. Why?Choose an answer to see the explanation.
Question 2 of 7The page's CSS has
button { background: saddlebrown; }. Which buttons turn saddlebrown?Choose an answer to see the explanation.
Question 3 of 7Which elements can the rules in
@scope (tea-filter) to (ul) { … }style?Choose an answer to see the explanation.
Question 4 of 7A page writes
@scope (tea-card) { button { font-weight: bold; } }. The card's Add button is in the card's open shadow root. Is it bold?Choose an answer to see the explanation.
Question 5 of 7Two scopes match the same paragraph. What color does this page print?
Read the code, then predict<style> @scope (tea-menu) { p { color: seagreen; } } @scope (main) { p { color: crimson; } } </style> <main> <tea-menu><p>3 teas</p></tea-menu> </main> <script> console.log(getComputedStyle(document.querySelector("p")).color); </script>Choose an answer to see the explanation.
Question 6 of 7The kit ships
@layer tea-kit { tea-filter button { background: seagreen; } }. The page writesbutton { background: saddlebrown; }, in no layer. What color is the filter's button?Choose an answer to see the explanation.
Question 7 of 7Where should
tea-menu:not(:defined) { min-block-size: 6rem; }go?Choose an answer to see the explanation.
Key takeaways
- Page CSS styles every tag from outside: its display, its place in the layout, and its look while
:not(:defined). - A custom element is
display: inlineuntil CSS says otherwise. For a light DOM component, the page's CSS is the only CSS it has. - Tokens on
:rootreach every component, through page rules and into shadow roots. - Rules for a tag that isn't defined yet belong in the page's CSS. Keep the room, and hide only with a timeout.
- Page rules reach everything inside a light DOM component. Start its rules with the tag name, and keep them shallow.
@scope (tea-filter) to (ul)styles the filter, not its list. A page's@scopenever reaches into a shadow root. When two scopes tie, the nearer root wins.- Prefix class names inside light DOM components, and put a library's rules in a layer, so the page wins.
Remember the one-liner.
The page places every stall. Open counters take the hall's lamps, so label yours and let the hall win.
Sources
The facts on this page come from these standards, docs, and posts:
- @scope, MDN.
- CSS Cascading and Inheritance Level 6: Cascade Sorting Order and @scope, W3C CSS Working Group.
- :defined, MDN.
- HTML Standard: the :defined pseudo-class, WHATWG.
- Using CSS custom properties: declaring them on :root, MDN.
- Styling Web Components, Chrome for Developers, Modern Web Guidance.
- Global and local styling, Every Layout, Heydon Pickering and Andy Bell.
- CSS-Only Custom Elements, Burton Smith.
- Reducing FOUC with Web Components, Burton Smith.
- Revisiting FOUCE, Cory LaViska.
- CSS Web Components for marketing sites, Hawk Ticehurst.
- Shadow DOM and the problem of encapsulation, Nolan Lawson.
- Modern CSS Feature Support For Shadow DOM: @scope, Adobe Spectrum Web Engineering.
- Organizing your CSS: BEM, MDN.
- @layer, MDN.
Coming next: Container queries in components. The page decides how much room a component gets. The next lesson makes the component fit whatever room that is.