completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

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.

By the end, you can
  • 01
    Style 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.
  • 02
    Scope light DOM stylesStyle a light DOM component by its tag name or with @scope, stop a scope with to, and know that neither reaches a shadow root.
  • 03
    Avoid 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:

One page rule, a light DOM filter, and a shadow DOM cardPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 2 styles both tags: a block, with a sea green border. Line 3 styles every button. font: inherit makes 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-filter with an empty class, so it has no shadow root.
  • Line 6 is a card. In the tea-card.js tab, 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.

At the top, a window labelled page CSS holds two rules: button { … } and tea-filter, tea-card { … }. Below it, two windows. The left one, tea-filter, holds a card <button>Search, and an arrow from the button rule reaches it. The right one, tea-card, holds a card <button>Add under the words shadow root, and no arrow reaches it. The tea-filter, tea-card rule has an arrow to the top of each window.page CSSbutton { … }tea-filter, tea-card { … }tea-filter<button>Searchlight DOM: the rules reach intea-cardshadow root<button>Addshadow DOM: the rules stop
The page's rules reach both tags. Inside 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.

Real-life analogyThe food hall and its stalls

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: display and 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 main idea

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:

A light DOM menu with no display rulePop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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:

Two cards and a menu on the page's grid, sharing one radiusPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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-radius for its corners.
  • In the tea-card.js tab, 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.

Real-life analogyThe shop's floor plan

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:

Keep the menu's room while its script loadsPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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: hidden on 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:

The page's paragraph rule meets the menu's own paragraphPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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 > p matches 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:

A deep selector and a shallow one for the same paragraphCSS
/* 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 scores 0-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:

How page rules reach a light DOM component and a shadow DOM one
What the page writesA light DOM component, like tea-filterA shadow DOM component, like tea-card
tea-card { display: block; } on the tagIt styles the tag.It styles the tag, and beats the card's own :host rule.
button { … } for the whole pageIt 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:

  • :scope inside 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:

Playground: where does the scope stop?
One scoped rule for a filter's buttonsPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
Stop at the list

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.

Only line 2 changes: the scope's root, and its limit. 700 means bold, and 400 means normal.
  • 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.

A window labelled tea-filter, the scope's root. Its first row holds two cards, <form> and <button>Search, labelled in scope. Its second row is a faded, crossed-out card <ul>, labelled the limit: out of scope. Its third row holds two faded, crossed-out cards, <li>Green tea and <button>Add, labelled inside it: out of scope. Under the window: @scope (tea-filter) to (ul).tea-filter<form><button>Search<ul><li>Green tea<button>Addin scopethe limit: out of scopeinside it: out of scope@scope (tea-filter) to (ul)
The scope starts at tea-filter and includes it. It stops at the <ul>: the list and everything inside it are out.
Real-life analogyPainting a room around a tenant's shelf

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: :scope styling 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:

A filter that carries its own scoped stylePop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Lines 2 to 7 are a <style> inside tea-filter. Line 3 has no root, only to (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:

A page @scope for a shadow DOM cardPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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:

Playground: which scope wins?
A menu inside a section of specialsPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
The nearer root wins

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.

Only lines 2 and 3 change. rgb(46, 139, 87) is sea green, and rgb(160, 82, 45) is sienna.
  • 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.

A small tree. At the top, a card section.specials. Under it, on the left, a card <p> Today's specials, labelled sienna: only .specials matches. On the right, a card tea-menu, and under it a card <p> 3 teas. Beside 3 teas: 1 step up to tea-menu, 2 steps up to .specials. Under it: sea green, tea-menu is nearer.section.specials<p> Today's specialstea-menu<p> 3 teassienna: only .specials matches1 step up to tea-menu2 steps up to .specialssea green: tea-menu is nearer
Both scopes hold the paragraph 3 teas. Its 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.

Real-life analogyThe nearest supervisor's word

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:

Classes that start with the component's tag nameCSS
/* 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:

Playground: can the page's rule win?
The kit's CSS, then the page'sPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
The kit wins on specificity

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.

Only line 3 changes: the kit's rule. The page's rule on line 7 stays the same. rgb(139, 69, 19) is saddlebrown.
  • 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.

Two cards, one above the other, with an arrow down between them. The first: @layer tea-kit: tea-filter button, 0-0-2. The second: no layer, the page: button, 0-0-1. Under them, the note: rules in no layer come after every layer. Below that, a card: Search: saddlebrown.Layers come before specificity@layer tea-kit: tea-filter button, 0-0-2no layer, the page: button, 0-0-1rules in no layer come after every layerSearch: saddlebrown
The kit's rule is more specific, but it sits in a layer. The page's rule sits in none, and rules in no layer come after every layer. Layers are compared first, so the page wins.
Real-life analogyThe printed menu and the chalkboard

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:

Does the page's rule reach it?
  • button { … } and the Search button inside tea-filter
  • button { … } and the Add button in tea-card's shadow root
  • tea-card { display: block; } and the tea-card tag
  • @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 corners
  • p { … } and the summary paragraph tea-menu adds
Try it yourself
0 of 7 correct

Sort each pair: a page rule, and the element it might style.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

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:

tea-kit/light.css, the kit's styles for its light DOM componentsCSS
/* 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 > p means 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-radius for the corners.

Now one page uses both kinds of component, each styled its own way:

One page, a light DOM filter and a shadow DOM cardPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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 the add part.
  • 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: inline until 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.

Exercise 1 · Warm-upCount the brown buttons

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>
ResultLoading…

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upPredict a scope that stops at each tea

    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>
    ResultLoading…

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeStop the note from jumping

      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>
      ResultLoading…

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeFix a selector that broke

        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>
        ResultLoading…

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeRename a class that clashes

          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>
          ResultLoading…

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeLet the page's rule win

            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>
            ResultLoading…

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              For each question, ask: is the element in the page's tree, and which step of the cascade decides?

              The page styles quiz · 7 questionsScore: first tries count
              1. 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.

              2. Question 2 of 7The page's CSS has button { background: saddlebrown; }. Which buttons turn saddlebrown?

                Choose an answer to see the explanation.

              3. Question 3 of 7Which elements can the rules in @scope (tea-filter) to (ul) { … } style?

                Choose an answer to see the explanation.

              4. 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.

              5. Question 5 of 7Two scopes match the same paragraph. What color does this page print?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <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.

              6. Question 6 of 7The kit ships @layer tea-kit { tea-filter button { background: seagreen; } }. The page writes button { background: saddlebrown; }, in no layer. What color is the filter's button?

                Choose an answer to see the explanation.

              7. 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: inline until CSS says otherwise. For a light DOM component, the page's CSS is the only CSS it has.
              • Tokens on :root reach 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 @scope never 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:

              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.

              CompleteFrontend Clear concepts. Working examples.