completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Styling the host

Learn how the CSS :host selector styles a web component's own element, how :host() reacts to its attributes, and why to avoid :host-context().

By the end, you can
  • 01
    Style the element itselfUse :host in a shadow root's styles, and know that the page's own rules for the tag still win.
  • 02
    Set a display and keep hidden workingGive the host a display, and add :host([hidden]) { display: none; }, because the browser's [hidden] rule loses to yours.
  • 03
    Make variants the right wayStyle the host by its attributes with :host(), and theme with a custom property or an attribute instead of :host-context().

What does the CSS :host selector do?

Leaf and Kettle is printing a new menu. Asha wants a small badge beside each tea: Green, Oolong, Black, or Organic. The kit already has <tea-badge>, from lesson 3.1. But it's an empty class, so each badge is plain text.

Asha gives the badge a shadow root, with a <style> inside. Her first rule is tea-badge { background: darkgreen; }. She reloads, and nothing changes. The badge's own name, in the badge's own style, matches nothing. So how does a component style itself?

Inside a shadow root's styles, the :host selector matches the shadow host: the element the shadow root belongs to, like <tea-badge>. :host(selector) does the same, but only while the host also matches the selector, such as [kind="green"]. On the page, both match nothing.

Here is the badge that works:

A badge that styles itself with :hostPop out in the code editor (opens in a new tab)HTML
<p>Today's tea: <tea-badge>Organic</tea-badge></p><script src="tea-badge.js"></script><script>  const badge = document.querySelector("tea-badge");  const style = getComputedStyle(badge);  console.log(style.backgroundColor, style.color);</script>
ResultLoading…
  • Line 1 of the page puts a badge in a sentence.
  • In the tea-badge.js tab, line 4 attaches a shadow root. Line 7 is the rule: :host, with a dark green background and white text.
  • Line 9 of tea-badge.js is a <slot>. It shows the page's text, Organic, inside the badge. Lesson 8.1 covers slots.
  • Back in the page, line 5 reads the badge's final styles with getComputedStyle(), which Styles and classes covers. Line 6 prints two of them.

It prints rgb(0, 100, 0) rgb(255, 255, 255): dark green and white. The rule styled the badge itself, the element on the page.

Now try Asha's first rule, and two more. The page gives the badge a class, new:

Playground: which selector reaches the badge?
A badge with the class new, and one rule in its shadow rootPop out in the code editor (opens in a new tab)HTML
<p>Today's tea: <tea-badge class="new">Organic</tea-badge></p><script src="tea-badge.js"></script><script>  const badge = document.querySelector("tea-badge");  console.log("Background:", getComputedStyle(badge).backgroundColor);</script>
ResultLoading…
Try it yourself
It matches nothing.

Background: rgba(0, 0, 0, 0). Inside its own shadow root, the badge has no tag name. tea-badge matches nothing there, so the background stays transparent.

The page stays the same: a badge with the class new. Each choice changes only the selector on line 7 of the tea-badge.js tab.
  • tea-badge and .new print rgba(0, 0, 0, 0), which is transparent. They match nothing.
  • :host and :host(.new) print rgb(0, 100, 0). Both reach the badge.

Why can't the shadow root use the badge's own name? Lesson 6.3 showed that selectors stay in their own tree. The host isn't inside its own shadow root. And the CSS Shadow spec adds a rule: inside its shadow tree, the host is featureless. It has no tag name, no classes, and no attributes that a plain selector could match. Only :host, :host(), and :host-context() can match it.

The spec gives the reason. The host's tag and classes belong to the page's author. If a component's .new rule could match the host, a class the page happens to use would restyle the component by accident. :host makes it clear that you mean the element itself.

A window called page holds the tea-badge element, labelled the host. Inside the page, a smaller window called shadow root holds two rules. An arrow leads from the :host rule to the badge, labelled matches the host. The rule tea-badge is crossed out, labelled matches nothing.page<tea-badge>the hostshadow root:hosttea-badgematches the hostmatches nothing
Inside its shadow root, the badge has no tag name and no class. Only :host reaches it, from inside.
Real-life analogyHome, not the street address

Ravi lives at 12 Tea Street. His neighbors write that address on their letters. But inside the house, nobody says "paint the door of 12 Tea Street". They say "paint our front door". From inside, the house is just home.

In real life: The street address
In JavaScript: The tag name tea-badge, and the classes the page gives it
In real life: The family inside the house
In JavaScript: The rules in the badge's shadow root
In real life: Saying "our front door"
In JavaScript: :host
In real life: The neighbors outside
In JavaScript: The page's own rules
The main idea

:host is how a shadow root's CSS points at the element it belongs to. Use it to give your component its own look: a display, a background, some padding. :host(selector) adds a condition, like an attribute. Neither one matches anything outside a shadow root.

Where does :host work?

Only inside a shadow root's styles. In the page's own style sheet, :host matches nothing, as lesson 6.3 showed with querySelector(). A page rule like :host { color: crimson; } is kept, but it never styles anything. MDN says the same.

Specificity is the score CSS uses to choose between two rules for the same element. The spec gives :host the score of one pseudo-class, the same as :hover. The hidden attribute section shows why that score matters.

Does :host > p style the page's paragraphs?

No, though many people try it. They want to style the paragraphs the page puts inside their tag. Here, the page puts Fresh today inside the card:

:host > p and a paragraph from the pagePop out in the code editor (opens in a new tab)HTML
<tea-card>  <p>Fresh today</p></tea-card><script src="tea-card.js"></script><script>  const card = document.querySelector("tea-card");  const inside = card.shadowRoot.querySelector("p");  const fromPage = card.querySelector("p");  console.log("Card's own p:", getComputedStyle(inside).fontWeight);  console.log("Page's p:", getComputedStyle(fromPage).fontWeight);</script>
ResultLoading…
  • Lines 1 to 3 are the card, with a paragraph from the page inside it.
  • In the tea-card.js tab, line 7 makes :host > p bold. Line 9 is the card's own paragraph, Green tea. Line 10 is a slot, which shows the page's paragraph.
  • Back in the page, line 7 finds the card's own paragraph, inside the shadow root. Line 8 finds the page's paragraph.

It prints Card's own p: 700 and Page's p: 400. Bold is 700, and normal is 400. Only the card's own paragraph is bold.

For selectors, the spec says the host stands in for its shadow root. So in :host > p, the host's children are the shadow root's top-level elements. The page's paragraph lives in the page's tree, even while a slot shows it inside the card. Styling it from inside is the job of ::slotted(), in the next lesson, Styling slotted content.

Why is a custom element inline by default?

Asha's badge sits in a sentence, so it can stay small. A card can't. Ravi wants each tea card to be 160px wide. He writes width: 160px on :host. The width does nothing.

The reason is the default display. The browser's own style sheet gives each built-in tag its display: a <div> or a <p> is a block. It has no rule for your tag. So a custom element gets the starting value of display, which is inline. web.dev's checklist warns that a width or height on it has no effect.

A card that asks for 160px and doesn't get itPop out in the code editor (opens in a new tab)HTML
<p>Today's tea: <tea-card>Green tea</tea-card> is ready.</p><script src="tea-card.js"></script><script>  const card = document.querySelector("tea-card");  console.log("display:", getComputedStyle(card).display);  console.log("160px wide:", card.getBoundingClientRect().width === 160);</script>
ResultLoading…
  • Line 1 puts a card in the middle of a sentence.
  • In the tea-card.js tab, line 7 asks for a 160px width and a sea green outline. An outline is a line drawn around the box. It doesn't change the layout.
  • Line 5 of the page prints the card's display. Line 6 checks whether the card's box is 160px wide.

It prints display: inline and 160px wide: false. The outline hugs the words Green tea.

An inline box behaves like a word in a sentence. It flows with the text, and it can even break across two lines. CSS ignores its width and height. That's what the default means for layout: until you choose, your component acts like a few words.

So give the host a display. Try three more:

Playground: which display should the host have?
A card in the middle of a sentencePop out in the code editor (opens in a new tab)HTML
<p>Today's tea: <tea-card>Green tea</tea-card> is ready.</p><script src="tea-card.js"></script><script>  const card = document.querySelector("tea-card");  console.log("display:", getComputedStyle(card).display);  console.log("160px wide:", card.getBoundingClientRect().width === 160);</script>
ResultLoading…
Try it yourself
Inline, and the width does nothing.

display: inline. 160px wide: false. With no display of its own, the card is inline, like a word in the sentence. Inline boxes ignore width, so the green outline hugs the text.

The page stays the same. Each choice changes only the display in the card's :host rule, line 7 of the tea-card.js tab, which also asks for a 160px width and a green outline.
  • block starts on its own line, and pushes the rest of the sentence below. The width works.
  • inline-block stays in the sentence, but as a box. The width works.
  • contents gives the card no box at all. The outline is gone, and the text sits in the sentence as if the card weren't there.

flex and grid make a block box too, and also arrange what's inside it. And contents suits a host that is only a wrapper. Its children join its parent's layout. In a flex row, they become items of that row. In Chrome, a host with contents measures 0 by 0, and its border and padding aren't drawn.

Why it matters: web.dev's checklist says to set a display on :host, unless you want inline. A card that should take its own line wants block. A badge that sits in text can use inline-block.

Why does the hidden attribute stop working on a web component?

The hidden attribute hides an element: <tea-card hidden>. Lesson 10.1 gave its tabs a :host([hidden]) rule, and showed that without it, hidden stopped working. Here is that bug on its own:

A hidden card that still showsPop out in the code editor (opens in a new tab)HTML
<p>Our teas</p><tea-card hidden>Green tea</tea-card><script src="tea-card.js"></script><script>  const card = document.querySelector("tea-card");  console.log("hidden:", card.hidden);  console.log("display:", getComputedStyle(card).display);</script>
ResultLoading…
  • Line 2 of the page writes a card with hidden.
  • In the tea-card.js tab, line 7 makes the host a block.
  • Line 6 of the page prints the hidden property. Line 7 prints the card's display.

It prints hidden: true and display: block. The attribute is there, and the card still shows.

Where does hidden get its power? From one rule in the browser's own style sheet. The HTML Standard lists it. In short, it says [hidden] { display: none; }, with two small exceptions. Nothing else hides the element. So any rule that sets display can undo it. The standard even warns that a rule giving every element display: block cancels hidden.

Why does the less specific rule win?

Here is the surprise. The browser's rule is the more specific one. Its full selector checks the attribute twice and a tag name once. :host is one pseudo-class. Yet :host wins.

CSS sorts rules by where they come from before it looks at specificity. Each source is called an origin. Three matter here:

  • the browser's own style sheet, the user-agent origin (the user agent is the browser);
  • the reader's own settings, the user origin;
  • your CSS, the author origin. A page's style sheets and a component's shadow root styles both count.

The CSS Cascade spec puts normal author rules above normal user-agent rules. So the browser's rule loses before specificity is even compared.

Two contests. Top row, first: the browser's rule [hidden] { display: none } is crossed out, and your rule :host { display: block } wins, because your style sheet beats the browser's. Bottom row, then: among your own rules, :host { display: block } is crossed out, and :host([hidden]) { display: none } wins, because it is more specific.first, whose style sheet?[hidden] { display: none }the browser's:host { display: block }yours: winsthen, among your own rules:host { display: block }less specific:host([hidden]) { display: none }more specific: wins
The browser's [hidden] rule loses to any display you set, because it comes from the browser's own style sheet. Specificity only picks between your own rules, so :host([hidden]) wins.
Real-life analogyFactory settings on a new phone

A new phone comes with factory settings, like a ringtone and "silent at night". Anything you set yourself replaces them. So when you choose "always ring", the phone rings at night too. To get quiet nights back, you add your own "silent at night".

In real life: The factory settings
In JavaScript: The browser's own style sheet, the user-agent origin
In real life: The factory's "silent at night"
In JavaScript: [hidden] { display: none; }
In real life: Your own "always ring"
In JavaScript: :host { display: block; }
In real life: Your own "silent at night", added back
In JavaScript: :host([hidden]) { display: none; }

How do you make hidden work again?

Write your own rule for it: :host([hidden]) { display: none; }. It matches the host only while it has hidden. Now both rules are yours, so specificity decides. Try it, and four other versions:

Playground: does hidden still hide the card?
A card with the hidden attributePop out in the code editor (opens in a new tab)HTML
<p>Our teas</p><tea-card hidden>Green tea</tea-card><script src="tea-card.js"></script><script>  const card = document.querySelector("tea-card");  console.log("hidden:", card.hidden);  console.log("display:", getComputedStyle(card).display);</script>
ResultLoading…
Try it yourself
Shown, even with hidden.

hidden: true. display: block. Your display: block beats the browser's display: none. The browser's own styles always lose to yours, so the card shows.

The page stays the same: a card with the hidden attribute. Each choice changes only the card's rules, from line 7 of the tea-card.js tab.
  • No display rule: display: none. Nothing fights the browser's rule.
  • :host { display: block; }: display: block. The card shows.
  • Add :host([hidden]): display: none again.
  • :host([hidden]) first: still none. The order doesn't matter.
  • :host { display: contents; }: display: contents. Any display you set beats hidden.

Why doesn't the order matter? The spec gives :host() the score of a pseudo-class plus its argument. :host([hidden]) counts a pseudo-class and an attribute. :host counts only a pseudo-class. The higher score wins, wherever the rule sits. MDN notes that this is different from :is() and :not(), which only count their argument.

Why it matters: write the two rules together every time you set a display. Then the page can hide your component with hidden, like any other element. The kit's tabs already do, and this lesson's badge will too.

How does :host() style the host by its attributes?

Back to Asha's badges. Each kind of tea should get its own color. The page already says which kind each badge is, with a kind attribute. :host() can read it:

A color for each kind of teaPop out in the code editor (opens in a new tab)HTML
<p>  <tea-badge kind="green">Green</tea-badge>  <tea-badge kind="oolong">Oolong</tea-badge>  <tea-badge kind="black">Black</tea-badge>  <tea-badge>Organic</tea-badge></p><script src="tea-badge.js"></script><script>  for (const badge of document.querySelectorAll("tea-badge")) {    console.log(badge.textContent, getComputedStyle(badge).backgroundColor);  }</script>
ResultLoading…
  • Lines 2 to 5 of the page are four badges. Three have a kind. Organic has none.
  • In the tea-badge.js tab, line 7 is the default: white text on dim gray, with a little space at each side.
  • Lines 8 to 10 each match one kind, and give it a background: dark green, sienna, or black.
  • Lines 9 to 11 of the page print each badge's background.

It prints Green rgb(0, 100, 0), Oolong rgb(160, 82, 45), Black rgb(0, 0, 0), and Organic rgb(105, 105, 105). Each kind gets its color, and Organic keeps the gray default. Lines 8 to 10 beat line 7 because they score higher, as in the last section.

On the left, the host as the page wrote it: tea-badge with kind="green". On the right, three rules from its shadow root, with arrows from the host to the first two. :host([kind="green"]) matches. :host([kind="black"]) doesn't match. :host(main tea-badge) is crossed out: Chrome drops it, because it holds a combinator.<tea-badge kind="green">the host:host([kind="green"])matches:host([kind="black"])doesn't match:host(main tea-badge)dropped: a combinator
:host() asks one question: does the host itself match? A selector that looks at another element, like main tea-badge, isn't allowed, so Chrome drops the rule.
Real-life analogyTea tins colored by their label

At Leaf and Kettle, every tea tin has the same shape. A label on each one says which tea is inside. The shop's rule is simple: a tin labelled green gets a green lid, and one labelled black gets a black lid. The rule reads only the tin's own label. It never asks which shelf the tin is on.

In real life: A tea tin
In JavaScript: A <tea-badge>
In real life: The label on the tin
In JavaScript: The kind attribute the page writes
In real life: A green label gets a green lid
In JavaScript: :host([kind="green"]) { background: darkgreen; }
In real life: Never asking about the shelf
In JavaScript: :host() checks the host alone, not what's around it

Now change the attribute yourself:

Playground: which kind is this badge?
One badge, with a kind attributePop out in the code editor (opens in a new tab)HTML
<p>Today's tea: <tea-badge kind="green">Green</tea-badge></p><script src="tea-badge.js"></script><script>  const badge = document.querySelector("tea-badge");  console.log("Background:", getComputedStyle(badge).backgroundColor);</script>
ResultLoading…
Try it yourself
Background: rgb(0, 100, 0).

Line 8 matches. It's more specific than line 7, so its dark green wins.

The badge's file stays the same as above. Each choice changes only the kind attribute on line 1 of the page.

Look at Green, with a capital G. The badge stays gray. For an attribute like kind, the selector compares the value exactly, capitals included. Why it matters: say which values your component accepts, in lowercase, and document them.

What can go inside :host()?

One compound selector. That's simple selectors written together with no spaces, like tea-badge.new[kind="green"]. The spec tests it against the host alone, as the page sees it. A list with commas isn't allowed. Neither is a combinator: a space, >, +, or ~ between two selectors. A combinator asks about another element.

Which :host() rules Chrome keepsCSS
/* Kept: one compound selector */
:host(.new) { font-weight: bold; }
:host([kind="green"]) { font-weight: bold; }
:host(tea-badge.new[kind="green"]) { font-weight: bold; }
:host(:hover) { font-weight: bold; }

/* Dropped: a list, or a combinator */
:host(.new, .sale) { font-weight: bold; }
:host(main tea-badge) { font-weight: bold; }
:host(main > tea-badge) { font-weight: bold; }
  • Lines 2 to 5 are kept: a class, an attribute, a tag with a class and an attribute, and a pseudo-class.
  • Lines 8 to 10 are dropped. Line 8 is a list. Lines 9 and 10 ask about main, another element.

When Chrome reads this sheet, it keeps four rules and drops three. A dropped rule is gone for every badge. And querySelector() with the same selector throws a SyntaxError.

One look-alike fools people: :host.new, with the class outside the brackets. Chrome keeps that rule, but it matches nothing. Outside the brackets, the host is featureless again.

Sort these rules for a badge written as <tea-badge kind="green" class="new">:

Which host rules work?
  • :host
  • :host(*)
  • :host([kind="green"])
  • :host(.new)
  • :host([kind="black"])
  • tea-badge
  • :host.new
  • :host(.new, .sale)
  • :host(main tea-badge)
Try it yourself
0 of 9 correct

Sort each selector, written inside the badge's shadow root, by what it does to the badge.

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

:host(*) belongs with :host. The star matches any element, and it adds nothing to the score. So the two act as the same selector. When both set a property, the later rule wins.

Styling the host on hover and focus

Pseudo-classes work inside :host() too. This card reacts to the reader:

A card that reacts to hover and focusPop out in the code editor (opens in a new tab)HTML
<tea-card></tea-card><script src="tea-card.js"></script>
ResultLoading…
  • In the tea-card.js tab, line 8 draws a dashed sea green outline while the pointer is over the card.
  • Line 9 draws a solid one while focus is anywhere inside it, like on the Add button from line 12.

Move the pointer over the card in the result: the outline is dashed. Press Tab until Add has focus: it turns solid. Lesson 9.3 used the same :host(:focus-within) rule for the kit's quantity part. Custom states, in lesson 12.3, are styled the same way, with :host(:state(...)).

Can the page still change the badge?

Yes. Here the page writes its own rule for the tag:

The page's rule beats a :host() rulePop out in the code editor (opens in a new tab)HTML
<style>  tea-badge { background: crimson; }</style><p>Today's tea: <tea-badge kind="green">Green</tea-badge></p><script src="tea-badge.js"></script><script>  const badge = document.querySelector("tea-badge");  console.log("Background:", getComputedStyle(badge).backgroundColor);</script>
ResultLoading…
  • Line 2 of the page gives every badge a crimson background.
  • Line 4 is a green badge. Its file is the one from above, with :host([kind="green"]) on line 8.
  • Line 8 of the page prints the badge's background.

It prints Background: rgb(220, 20, 60), which is crimson. The page's selector is one tag name. The badge's selector is a pseudo-class and an attribute, so it scores higher. And it still loses.

That surprises many people. For normal rules, the cascade lets the page beat the shadow root before it compares specificity. Lesson 11.1 met this with a reset. Lesson 11.4, The shadow cascade and which styles win, explains the full order. Why it matters: treat your :host rules as defaults. The people who use your component can always change them.

What is :host-context() and why should you avoid it?

Ravi wants dark badges in the menu's evening section, a <div class="dark">. :host() can't help: :host(.dark tea-badge) has a combinator, so it's dropped. Older tutorials use :host-context() for this. Lesson 2.3 met it briefly. Here is how it works, and why to leave it alone.

A badge that checks its ancestors with :host-context()Pop out in the code editor (opens in a new tab)HTML
<div class="dark">  <tea-badge>Green</tea-badge></div><tea-badge>Oolong</tea-badge><script src="tea-badge.js"></script><script>  for (const badge of document.querySelectorAll("tea-badge")) {    console.log(badge.textContent, getComputedStyle(badge).backgroundColor);  }</script>
ResultLoading…
  • Lines 1 to 3 of the page put a badge in a dark area. Line 4 is a badge outside it.
  • In the tea-badge.js tab, line 7 is the gray default. Line 8 makes the badge black when .dark matches the badge or any element above it.
  • Lines 7 to 9 of the page print each badge's background.

In Chrome, it prints Green rgb(0, 0, 0) and Oolong rgb(105, 105, 105). The badge in the dark area is black. Chrome even looks past other shadow roots on the way up, all the way to the document. Remove the class, and the badge turns gray again.

In Firefox and Safari, both badges stay gray. Neither browser ever shipped :host-context(). A selector the browser doesn't know makes the whole rule invalid, so line 8 is dropped there.

Why is :host-context() going away?

The idea was theming. A page puts a class high up, and every component below it reacts. Three problems stopped it:

  • It's slow to keep up to date. A class change on any element might restyle every component below it, even inside shadow roots. In the CSS Working Group's issue 1914, an engineer looking into adding it to Firefox's engine explained that the browser has to visit all those components to check.
  • Two of the three browser engines said no. Firefox and Safari never shipped it. Apple's WebKit team wrote that styling an element by where it appears isn't a good way to design a reusable element.
  • Better tools arrived. Custom properties and container style queries cover most of the same needs.

So the CSS Working Group decided to remove it. MDN marks it deprecated, and Chrome's own styling guide says to avoid it. Chrome still runs it, so old code keeps working there. New code shouldn't depend on it.

Real-life analogyA teapot that checks the table

Picture a teapot that picks its color by looking at its table, then the room, then the whole café. Move a table, and every teapot has to look again. A simpler café puts a coaster under each teapot. The coaster says which color to use, and the teapot just reads it.

In real life: The teapot
In JavaScript: The badge
In real life: Checking the table, the room, and the café
In JavaScript: :host-context(.dark) checking every ancestor
In real life: The coaster under it
In JavaScript: A custom property, like --tea-badge-bg, that the page sets
In real life: Reading the coaster
In JavaScript: var(--tea-badge-bg, dimgray) inside the badge

What to use instead of :host-context()

Two designs work in every browser. In both, the page decides, and the badge only reads what it's given. The first is a custom property. The page sets it on the dark area, and it inherits down into the badge, as lesson 11.1 showed:

A custom property set by the page and read by the badgeCSS
/* On the page */
.dark { --tea-badge-bg: black; }

/* In the badge's shadow root */
:host { background: var(--tea-badge-bg, dimgray); }
  • Line 2 is in the page. Every element inside .dark inherits --tea-badge-bg: black.
  • Line 5 is in the badge's shadow root. var() reads the property. Its second value, dimgray, is the fallback, used when nothing set it.

The second is an attribute on the badge itself, like theme="dark", matched with :host([theme="dark"]). Compare all three:

Playground: three ways to theme the badge
A badge in a dark area, and one outside itPop out in the code editor (opens in a new tab)HTML
<div class="dark">  <tea-badge>Green</tea-badge></div><tea-badge>Oolong</tea-badge><script src="tea-badge.js"></script><script>  for (const badge of document.querySelectorAll("tea-badge")) {    console.log(badge.textContent, getComputedStyle(badge).backgroundColor);  }</script>
ResultLoading…
Try it yourself
Chrome only.

Green rgb(0, 0, 0). Oolong rgb(105, 105, 105). Line 8 of tea-badge.js looks for .dark on the badge and on every element above it. In Chrome, the first badge turns black. Firefox and Safari don't know :host-context(), so there both badges stay gray.

Each choice is a whole page: a badge inside a dark area and one outside it. Open the tea-badge.js tab to see how the badge finds out.

In Chrome, all three print the same two lines. Only the last two work in every browser.

Two halves. Left, :host-context(.dark): three cards stacked, body, then a div with class dark, then tea-badge at the bottom. Arrows point up from the badge to the div and from the div to body, labelled looks up. Right, var(--tea-badge-bg): the page sets --tea-badge-bg: black, and an arrow labelled inherited points down to the tea-badge card, which reads it.:host-context(.dark)<body><div class="dark"><tea-badge>looks upvar(--tea-badge-bg)the page sets--tea-badge-bg: blackinherited<tea-badge>the badge reads it
With :host-context(), the badge searches up through every ancestor. With a custom property, the page sends a value down, and the badge only reads what arrives.

Read each row across: what the badge uses, who decides, and where it works.

Three ways to make a badge dark
When the badge usesWho decidesWhere it works
:host-context(.dark)The badge searches its own ancestors for a class.Only in Chrome. The CSS Working Group decided to remove it.
var(--tea-badge-bg, dimgray)The page sets a value, and the badge reads what it inherits.In every browser.
:host([theme="dark"])The page sets an attribute on the badge itself.In every browser.

Why it matters: a component that searches around itself depends on markup it doesn't own. A component that reads a value is easy to theme from anywhere. Lesson 12.1, Custom properties as a styling API, designs those properties with care. Container style queries, the other tool the working group named, come in lesson 12.5.

Giving the tea badge a look of its own

Now the kit. Since lesson 3.1, tea-badge has been an empty class. This lesson's kit gives it a shadow root, a slot for its text, and a style:

  • :host makes it an inline-block badge: a little padding, rounded corners, and white text on dim gray.
  • :host([hidden]) { display: none; } keeps hidden working.
  • Three :host() rules color green, oolong, and black teas.

Switch between the two kits. The page stays the same: five badges, the last one hidden.

Playground: the kit's badge, before and after
<p>  <tea-badge kind="green">Green</tea-badge>  <tea-badge kind="oolong">Oolong</tea-badge>  <tea-badge kind="black">Black</tea-badge>  <tea-badge>Organic</tea-badge>  <tea-badge hidden>Sold out</tea-badge></p><script type="module">  import "./tea-kit/index.js";   for (const badge of document.querySelectorAll("tea-badge")) {    const style = getComputedStyle(badge);    console.log(badge.textContent, style.display, style.backgroundColor);  }</script>
ResultLoading…
Try it yourself
Plain words in a row.

Green inline rgba(0, 0, 0, 0). Oolong inline rgba(0, 0, 0, 0). Black inline rgba(0, 0, 0, 0). Organic inline rgba(0, 0, 0, 0). Sold out none rgba(0, 0, 0, 0). The badge from lesson 3.1 is an empty class with no styles. So every badge is inline text with no background, and kind does nothing.

The page stays the same. Only the kit changes: open the tea-kit/tea-badge.js tab to see the badge's new style.
  • Lines 2 to 6 are the badges. Line 6 has hidden.
  • Line 9 loads the kit. Lines 11 to 14 print each badge's text, display, and background.

With the kit from lesson 11.1, every badge prints inline and rgba(0, 0, 0, 0), and Sold out prints none. With this lesson's kit, the first four print inline-block and their colors. Sold out still prints none. Without the :host([hidden]) line, it would print inline-block and show.

The kit's JSDoc and its custom-elements.json now list the kind attribute and its three values, the way lesson 5.4 documented the timer.

Common mix-ups

  • "Inside the shadow root, I can select the host by its tag name." No. There, the host is featureless. tea-badge and .new match nothing. Only :host and :host() reach it.
  • "The hidden attribute always hides an element." No. It works through one rule in the browser's style sheet, and any display you set beats it. Add :host([hidden]) { display: none; }.
  • "The browser's hidden rule loses because it's less specific." No. It's more specific. It loses because author styles beat the browser's, before specificity counts.
  • ":host([hidden]) has to come after :host." No. It scores higher, so it wins in any order.
  • ":host > p styles the paragraphs I put inside my tag." No. It matches the shadow root's top-level paragraphs. Content from the page needs ::slotted(), in lesson 11.3.
  • ":host(main tea-badge) styles badges inside main." No. :host() takes one compound selector, so Chrome drops the whole rule.
  • "A more specific :host rule beats the page's rule for my tag." No. The page's rule wins anyway. Lesson 11.4 explains why.
  • ":host-context() is the standard way to theme components." No. Only Chrome runs it, and the CSS Working Group decided to remove it. Use a custom property or an attribute.

Practice exercises

Answer first, then use the hints. The pages run live, so you can check yourself.

Exercise 1 · Warm-upShown or hidden?

The card has the hidden attribute. What does the console print?

<tea-card hidden>Green tea</tea-card><script src="tea-card.js"></script><script>  console.log(getComputedStyle(document.querySelector("tea-card")).display);</script>
ResultLoading…

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

    Exercise 2 · Warm-upWhich rules survive?

    The badge's style has three :host() rules. How many does the browser keep?

    <tea-badge class="new">Organic</tea-badge><script src="tea-badge.js"></script><script>  const style = document.querySelector("tea-badge").shadowRoot.querySelector("style");  console.log(style.sheet.cssRules.length);</script>
    ResultLoading…

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

      Exercise 3 · PracticeMake hidden work again

      The Sold out badge has hidden, but it shows. Fix it in the tea-badge.js tab. What does your fixed page print?

      <p>  <tea-badge>Organic</tea-badge>  <tea-badge hidden>Sold out</tea-badge></p><script src="tea-badge.js"></script><script>  const soldOut = document.querySelector("tea-badge[hidden]");  console.log(getComputedStyle(soldOut).display);</script>
      ResultLoading…

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

        Exercise 4 · PracticeMark the selected card

        Give the card with the selected attribute a sea green outline, from inside the card. What does the Black tea line print?

        <tea-card>Green tea</tea-card><tea-card selected>Black tea</tea-card><script src="tea-card.js"></script><script>  for (const card of document.querySelectorAll("tea-card")) {    console.log(card.textContent, getComputedStyle(card).outlineStyle);  }</script>
        ResultLoading…

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

          Exercise 5 · ChallengeBigger badges in main

          Badges inside <main> should be 20px, but this one stays 16px. Find the bug and fix it. You may change the page too. What does your fixed page print?

          <main>  <tea-badge>Organic</tea-badge></main><script src="tea-badge.js"></script><script>  console.log(getComputedStyle(document.querySelector("tea-badge")).fontSize);</script>
          ResultLoading…

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

            Exercise 6 · ChallengeTheme without :host-context()

            This badge uses :host-context(.dark), so it only turns black in Chrome. Rewrite it with a custom property that the page sets, so it works in every browser.

            <div class="dark">  <tea-badge>Green</tea-badge></div><tea-badge>Oolong</tea-badge><script src="tea-badge.js"></script><script>  for (const badge of document.querySelectorAll("tea-badge")) {    console.log(badge.textContent, getComputedStyle(badge).backgroundColor);  }</script>
            ResultLoading…

              Check your understanding

              For each question, ask yourself: where does the rule come from, and what does it really match?

              The styling the host quiz · 7 questionsScore: first tries count
              1. Question 1 of 7Inside the tea badge's shadow root, which rule gives the badge itself a background?

                Choose an answer to see the explanation.

              2. Question 2 of 7Before any CSS sets it, what is a custom element's display?

                Choose an answer to see the explanation.

              3. Question 3 of 7A card has :host { display: block; }, and the page writes <tea-card hidden>. Why does the card still show?

                Choose an answer to see the explanation.

              4. Question 4 of 7What does this page print, with a page rule for the tag and a :host() rule inside?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <style>
                  tea-badge { background: darkorange; }
                </style>
                <tea-badge kind="green">Green</tea-badge>
                <script>
                  const root = document.querySelector("tea-badge").attachShadow({ mode: "open" });
                  root.innerHTML = '<style>:host([kind="green"]) { background: darkgreen; }</style><slot></slot>';
                  console.log(getComputedStyle(root.host).backgroundColor);
                </script>

                Choose an answer to see the explanation.

              5. Question 5 of 7Which of these rules does Chrome drop when it reads the shadow root's style sheet?

                Choose an answer to see the explanation.

              6. Question 6 of 7In a tea card's shadow root, what does :host > p select?

                Choose an answer to see the explanation.

              7. Question 7 of 7Why should a new component avoid :host-context()?

                Choose an answer to see the explanation.

              Key takeaways

              • :host matches the shadow host from inside its shadow root. On the page, it matches nothing.
              • Inside its shadow root, the host is featureless: tea-badge and .new miss it, but :host(.new) reaches it.
              • A custom element is inline until you set a display. Set one on :host.
              • Any display you set beats the browser's [hidden] rule, because author styles beat the browser's. Add :host([hidden]) { display: none; }.
              • :host() takes one compound selector, checks the host alone, and adds its argument's specificity. Lists and combinators are dropped.
              • The page's rule for your tag beats your :host rules. They are defaults.
              • Avoid :host-context(). Only Chrome runs it, and the CSS Working Group decided to remove it. Use a custom property or an attribute.

              Remember the one-liner.
              :host is a component's name for itself: give it a display, keep hidden working, read its attributes with :host(), and let the page have the last word.

              Sources

              The facts on this page come from these standards, docs, and discussions:

              Coming next: Styling slotted content. It styles the page's content inside your slots with ::slotted(), the job :host > p can't do.

              CompleteFrontend Clear concepts. Working examples.