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().
- 01Style the element itselfUse
:hostin a shadow root's styles, and know that the page's own rules for the tag still win. - 02Set 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. - 03Make 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:
<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>- Line 1 of the page puts a badge in a sentence.
- In the
tea-badge.jstab, 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.jsis 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:
<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>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.
tea-badgeand.newprintrgba(0, 0, 0, 0), which is transparent. They match nothing.:hostand:host(.new)printrgb(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.
:host reaches it, from inside.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
: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:
<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>- Lines 1 to 3 are the card, with a paragraph from the page inside it.
- In the
tea-card.jstab, line 7 makes:host > pbold. 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.
<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>- Line 1 puts a card in the middle of a sentence.
- In the
tea-card.jstab, 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:
<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>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.
- 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.
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:
<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>- Lines 2 to 5 of the page are four badges. Three have a
kind. Organic has none. - In the
tea-badge.jstab, 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.
: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.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
kindattribute 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:
<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>Line 8 matches. It's more specific than line 7, so its dark green wins.
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.
/* 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">:
:host:host(*):host([kind="green"]):host(.new):host([kind="black"])tea-badge:host.new:host(.new, .sale):host(main tea-badge)
Sort each selector, written inside the badge's shadow root, by what it does to the badge.
: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:
<tea-card></tea-card><script src="tea-card.js"></script>- In the
tea-card.jstab, 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:
<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>- 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.
<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>- 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.jstab, line 7 is the gray default. Line 8 makes the badge black when.darkmatches 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.
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:
/* 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
.darkinherits--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:
<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>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.
In Chrome, all three print the same two lines. Only the last two work in every browser.
: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.
| When the badge uses | Who decides | Where 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:
:hostmakes it aninline-blockbadge: a little padding, rounded corners, and white text on dim gray.:host([hidden]) { display: none; }keepshiddenworking.- 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.
<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>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.
- 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-badgeand.newmatch nothing. Only:hostand: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 > pstyles 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
:hostrule 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.
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>flex. The card's :host rule sets display: flex, and author styles beat the browser's [hidden] { display: none; }. The card shows, even with hidden.
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>1. In tea-badge.js, line 7 has a list, .new, .sale, and line 8 has a combinator, the space in main tea-badge. Chrome drops both. Only :host(.new) on line 9 is left.
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><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>In tea-badge.js, add :host([hidden]) { display: none; } to the style. It's your rule, and it scores higher than :host, so Sold out is hidden and the page prints none.
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><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>:host([selected]) matches only the card the page marked. The page prints Green tea none and Black tea solid.
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><main> <tea-badge size="large">Organic</tea-badge></main><script src="tea-badge.js"></script><script> console.log(getComputedStyle(document.querySelector("tea-badge")).fontSize);</script>:host(main tea-badge) has a combinator, so Chrome drops it. The page now writes size="large" on the badge, and the badge matches it with :host([size="large"]). The page prints 20px.
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><style> .dark { --tea-badge-bg: black; }</style><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>The page sets --tea-badge-bg: black on .dark. The badge inside inherits it, and var() reads it, with dimgray as the fallback. It prints Green rgb(0, 0, 0) and Oolong rgb(105, 105, 105), the same as before. Now it works in Firefox and Safari too.
Check your understanding
For each question, ask yourself: where does the rule come from, and what does it really match?
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.
Question 2 of 7Before any CSS sets it, what is a custom element's
display?Choose an answer to see the explanation.
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.
Question 4 of 7What does this page print, with a page rule for the tag and a
:host()rule inside?Read the code, then predict<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.
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.
Question 6 of 7In a tea card's shadow root, what does
:host > pselect?Choose an answer to see the explanation.
Question 7 of 7Why should a new component avoid
:host-context()?Choose an answer to see the explanation.
Key takeaways
:hostmatches the shadow host from inside its shadow root. On the page, it matches nothing.- Inside its shadow root, the host is featureless:
tea-badgeand.newmiss it, but:host(.new)reaches it. - A custom element is
inlineuntil 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
:hostrules. 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:
- :host, MDN.
- CSS Shadow Module Level 1: Selecting shadow hosts from within a shadow tree, CSS Working Group.
- CSS Shadow Module Level 1: The :host, :host(), and :host-context() pseudo-classes, CSS Working Group.
- Custom element best practices, web.dev.
- display, MDN.
- HTML Standard: The hidden attribute, WHATWG.
- HTML Standard: Hidden elements, WHATWG.
- CSS Cascading and Inheritance Level 5: Cascade origins, CSS Working Group.
- :host(), MDN.
- :host-context(), MDN.
- Dynamic changes of state and attributes referenced by :host-context rules (issue 1914), CSS Working Group.
- Styling web components, Chrome for Developers.
Coming next: Styling slotted content. It styles the page's content inside your slots with ::slotted(), the job :host > p can't do.