completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Styling slotted content

Learn how the CSS ::slotted() selector styles what a page puts in your web component's slots, why page styles win, and how :has-slotted helps.

By the end, you can
  • 01
    Style the page's content from insideWrite ::slotted() with one compound selector, and pick one slot with slot[name="name"]::slotted().
  • 02
    Know what ::slotted() can't reachIt matches only the top-level elements in a slot, never text or nested elements. Reach those through inherited properties.
  • 03
    Treat ::slotted() rules as defaultsKnow that the page's own rules win, and hide an empty slot's heading with :has-slotted or the slotchange check.

What does the CSS ::slotted() selector do?

At Leaf and Kettle, the tea card has slots, since lesson 8.1. The page puts its own markup inside the card: a heading with the tea's name, and a short tasting note. Asha wants two small changes, made from inside the card. The gap above the name should go. And the note should be seagreen.

She opens the card's shadow root and writes p { color: seagreen; }. Nothing changes. Lesson 11.1 said why: selectors in a shadow root only match the shadow root's own elements. The note belongs to the page. So how does a component style what the page puts in its slots?

Inside a shadow root's styles, ::slotted(selector) matches the elements the page put into the component's slots, when they match the selector. It reaches only those top-level elements: not text, and not the elements inside them. And the page's own rules for those elements still win.

Here is Asha's card:

A card that styles the heading and note the page gives itPop out in the code editor (opens in a new tab)HTML
<tea-card>  <h3 slot="name">Green tea</h3>  <p>Grassy and fresh.</p></tea-card><script src="tea-card.js"></script><script>  const [name, note] = document.querySelector("tea-card").children;  console.log("Name margin:", getComputedStyle(name).marginTop);  console.log("Note color:", getComputedStyle(note).color);</script>
ResultLoading…
  • Lines 1 to 4 of the page are the card. Line 2 is a heading for the name slot. Line 3 is the note.
  • In the tea-card.js tab, line 7 takes the margin off a slotted <h3>. Line 8 makes a slotted <p> seagreen.
  • Lines 10 and 11 of tea-card.js are the card's two slots: the name slot and the default slot.
  • Back in the page, line 7 takes the card's two children, the heading and the note. Lines 8 and 9 print the heading's top margin and the note's color.

It prints Name margin: 0px and Note color: rgb(46, 139, 87), which is seagreen. Without line 7, the browser would give the heading its normal top margin, 18.72px here.

Now try the rule Asha wrote first, and three more:

Playground: which rule reaches the page's note?
A note from the page, and one rule in the card's shadow rootPop out in the code editor (opens in a new tab)HTML
<tea-card>  <p>Grassy and fresh.</p></tea-card><script src="tea-card.js"></script><script>  const note = document.querySelector("tea-card p");  console.log("Note color:", getComputedStyle(note).color);</script>
ResultLoading…
Try it yourself
It matches nothing.

Note color: rgb(0, 0, 0). A plain p in the shadow root only looks at the shadow root's own elements. The paragraph belongs to the page, so it stays black.

The page stays the same: one note inside the card. Each choice changes only the selector on line 7 of the tea-card.js tab.
  • p, :host p, and slot p print rgb(0, 0, 0), the browser's normal black. They match nothing.
  • ::slotted(p) prints rgb(46, 139, 87). It reaches the note.

Why does slot p miss? In the shadow root, the slot has no children of its own. Lesson 8.2 showed that a slotted node stays a child of the host, in the page's tree. The browser only draws it in the slot's place. ::slotted() is the selector made for that place.

A window called page holds tea-card and, under it, the page's note, a p element. Inside the page, a smaller window called shadow root holds two rules. The rule p is crossed out, labelled matches nothing. An arrow leads from the ::slotted(p) rule across the shadow root's edge to the page's p, labelled reaches it.page<tea-card><p>the page's noteshadow rootpmatches nothing::slotted(p)reaches it
The note stays in the page's tree, even while a slot shows it inside the card. A plain p rule in the shadow root matches nothing there. ::slotted(p) reaches across to it.
Real-life analogyThe café sets the table, the guest brings the cup

At Leaf and Kettle, staff set each table before guests arrive: a mat, a napkin, a spot for the cup. Some guests bring their own cup. Staff can set it on the mat and turn the handle to the right. They don't repaint the guest's cup.

In real life: The table the café sets
In JavaScript: The card's shadow root
In real life: The guest's own cup
In JavaScript: An element the page put in a slot
In real life: Setting the cup on the mat
In JavaScript: A ::slotted() rule, like margin: 0
In real life: The pattern painted on the cup
In JavaScript: The page's own rules for that element
The main idea

::slotted() is how a shadow root styles the elements a page puts in its slots. Use it for small touches: some spacing, a color, a font weight. It matches only the top-level elements in a slot, and the page's own rules for them still win.

Where does ::slotted() work?

Only in a shadow root's styles. The CSS Shadow spec says it only exists on slots. In the page's own style sheet, a ::slotted(p) rule matches nothing. MDN says the same.

It's a pseudo-element: a selector for something that isn't a plain element in the markup, like ::before. That's why it has two colons. And querySelector() never finds it: querySelector("::slotted(p)") returns null, even on the shadow root.

What can go inside ::slotted()?

One compound selector, as with :host() in lesson 11.2. A compound selector is simple selectors written together with no spaces: a tag, a class, an attribute, or a pseudo-class, like p.note:hover. The brackets test each slotted element on its own.

Which ::slotted() rules Chrome keepsCSS
/* Kept: one compound selector in the brackets */
::slotted(*) { color: seagreen; }
::slotted(p.note) { color: seagreen; }
::slotted(p:hover) { color: seagreen; }
slot[name="name"]::slotted(h3) { color: seagreen; }

/* Dropped: a combinator, a list, or a pseudo-class after the brackets */
::slotted(p span) { color: seagreen; }
::slotted(p) span { color: seagreen; }
::slotted(p, ul) { color: seagreen; }
::slotted(p):hover { color: seagreen; }
  • Lines 2 to 5 are kept. Line 2 matches any slotted element. Line 3 needs a <p> with the class note. Line 4 matches a <p> while the pointer is over it.
  • Line 5 has something in front of ::slotted. slot[name="name"] picks the slot, so this rule only looks in the name slot.
  • Lines 8 to 11 are dropped. Lines 8 and 9 ask about a <span> inside a paragraph. Line 10 is a list. Line 11 puts :hover after the brackets.

When Chrome reads this sheet, it keeps four rules and drops four. A dropped rule is gone for every card. Firefox and Safari keep and drop the same ones.

How do you pick one slot?

::slotted(p) on its own means *::slotted(p): any slot. The spec says so. To look in one slot, put a selector for that slot in front. slot[name="name"]::slotted(h3) looks only in the name slot. slot:not([name])::slotted(p) looks only in the default slot, the one with no name, as lesson 8.4 did.

Sort these rules for a card whose page writes <p class="note">Grassy and fresh.</p> in its default slot:

Which rules style the note?
  • ::slotted(*)
  • ::slotted(p)
  • ::slotted(.note)
  • slot:not([name])::slotted(p)
  • slot[name="name"]::slotted(p)
  • p
  • ::slotted(span)
  • ::slotted(p span)
  • ::slotted(p):hover
Try it yourself
0 of 9 correct

Sort each rule, written inside the card's shadow root, by what it does to the note.

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

Styling slotted elements on hover and focus

Pseudo-classes go inside the brackets:

A note that turns seagreen under the pointerPop out in the code editor (opens in a new tab)HTML
<tea-card>  <p>Grassy and fresh.</p>  <p>Brew for 2 minutes.</p></tea-card><script src="tea-card.js"></script>
ResultLoading…
  • Lines 2 and 3 of the page are two notes.
  • In the tea-card.js tab, line 7 is ::slotted(p:hover). It matches a slotted paragraph while the pointer is over it.

Move the pointer over each note in the result. The one under the pointer turns seagreen. ::slotted(p):hover looks the same, but Chrome, Firefox, and Safari all drop it. Lesson 10.2 used the same pattern for keyboard focus: ::slotted(:focus-visible).

Why can't ::slotted() style nested elements?

Ravi puts more into a card: a few bare words, a note, and a box with brewing advice. He wants to see what the card can reach. So he outlines every slotted element:

Outlining every slotted elementPop out in the code editor (opens in a new tab)HTML
<tea-card>  Fresh today  <p>Grassy and fresh.</p>  <div>    <p>Brew for 2 minutes.</p>  </div></tea-card><script src="tea-card.js"></script><script>  for (const element of document.querySelectorAll("tea-card *")) {    console.log(element.localName, getComputedStyle(element).outlineStyle);  }</script>
ResultLoading…
  • Line 2 of the page is bare words, Fresh today. Line 3 is a note. Lines 4 to 6 are a div with a paragraph inside it.
  • In the tea-card.js tab, line 7 draws a seagreen outline around every slotted element. An outline is a line drawn around an element's box.
  • Line 10 of the page goes through every element inside the card, at any depth. Line 11 prints each one's tag and outline style.

It prints p solid, div solid, and p none. The note and the div have outlines. The paragraph inside the div has none of its own. And Fresh today has no outline either.

The children of tea-card, for the rule ::slotted(*). Arrows lead from tea-card to its three children: the words Fresh today, crossed out and labelled text; a p element; and a div element. An arrow leads from the div to a p inside it, crossed out and labelled inside the div.::slotted(*)<tea-card>Fresh todaytext<p><div><p>inside the div
::slotted(*) matches the card's two top-level elements, the <p> and the <div>. The words are text, and the inner <p> is the div's child, so neither one is matched.

Two rules explain it:

  • Only assigned elements match. ::slotted() matches elements assigned to a slot. Lesson 8.1 showed that only the host's own children get assigned. The inner paragraph is the div's child, so no slot holds it.
  • Text never matches. Fresh today is a text node, and ::slotted() only matches elements. MDN and the spec both say so.

So a selector that looks deeper gets dropped, as in the last section. ::slotted(div p) and ::slotted(div) p are both dropped. javascript.info warns about the same two shapes. And Manuel Matuzović lists it as a real pain of shadow DOM: a slotted <ul> can be styled, but not its <li> items.

Chrome's styling guide says the same in one line: ::slotted() targets the top-level nodes in a slot, and it can't reach their descendants.

Real-life analogyA porter tags each bag, not what's inside

At a hotel, a porter takes each bag you hand over and puts a tag on it. He never opens a bag to tag the shirts inside. Coins loose in your hand get no tag at all. There's nothing to tie a tag to.

In real life: The bags you hand over
In JavaScript: The host's children, like the note and the div
In real life: The tag on a bag
In JavaScript: A ::slotted() style
In real life: The shirts inside a bag
In JavaScript: The paragraph inside the div
In real life: Coins loose in your hand
In JavaScript: Text, like Fresh today

Why it matters: design each slot for the elements you expect at its top level. To style anything deeper, use the tool in the next section.

How do you style text and nested elements in a slot?

Through inheritance. Lesson 8.2 showed that a slotted node inherits from its slot, because inheritance follows the flat tree. Lesson 11.1 listed the properties that inherit, like color and font-family. Two places inside the card can start that flow:

  • the slot itself, for everything shown in it, text included;
  • a slotted element, through ::slotted(), for everything inside that element.

Try four rules on Ravi's div:

Playground: which rule reaches the paragraph inside the div?
Bare words and a div, inside the cardPop out in the code editor (opens in a new tab)HTML
<tea-card>  Fresh today  <div>    <p>Brew for 2 minutes.</p>  </div></tea-card><script src="tea-card.js"></script><script>  const inner = document.querySelector("tea-card p");  const style = getComputedStyle(inner);  console.log("Inner p:", style.color, style.borderTopStyle);</script>
ResultLoading…
Try it yourself
Dropped, so nothing changes.

Inner p: rgb(0, 0, 0) none. ::slotted() takes one compound selector. The space in div p is a combinator, so the browser drops the whole rule.

The page stays the same: the words Fresh today, then a div with a paragraph in it. Each choice changes only line 7 of the tea-card.js tab.
  • ::slotted(div p) prints Inner p: rgb(0, 0, 0) none. The rule is dropped.
  • ::slotted(div) color prints rgb(46, 139, 87). The div is seagreen, and the paragraph inherits it.
  • ::slotted(div) border prints rgb(0, 0, 0) none. The div gets a border, but border isn't inherited.
  • slot color prints rgb(46, 139, 87) too. And now Fresh today turns seagreen as well.

The spec says it plainly: the only way to style text in a slot is to style the slot and let the text inherit.

Two halves. Left, color is inherited: a card for the slotted div with color seagreen, and an arrow labelled inherits leads down to the p inside it, which has color seagreen too. Right, border isn't: the div has border solid, labelled stays on the div, and the inner p's border card is crossed out.color is inherited<div> color: seagreeninherits<p> color: seagreenborder isn't<div> border: solidstays on the div<p> border: solidthe inner p has none
::slotted(div) styles only the div. An inherited property like color flows on to the paragraph inside it. A property like border isn't inherited, so it stays on the div.
Real-life analogyHeating a room warms everything in it

Turn up the heating in a room, and everything in it warms up: the chairs, the books, even the tea in a closed tin. A fridge in the room stays cold. It has its own setting, and its setting wins.

In real life: Turning up the heating
In JavaScript: color: seagreen on the slot, or on ::slotted(div)
In real life: The chairs, the books, the tea in the tin
In JavaScript: The text and the elements inside, which inherit it
In real life: The fridge with its own setting
In JavaScript: An element with its own rule for that property

An inherited value is the weakest kind. Any rule that matches the element itself beats it, even the browser's own. So a link inside a seagreen paragraph keeps the browser's link blue, rgb(0, 0, 238).

Read each row across: what you want to style, how to do it from inside, and who has the last word.

Styling the content in a slot
When you want to styleWhat to write in the shadow rootWho has the last word
A paragraph the page put in a slot.::slotted(p) { color: seagreen; }The page. Any page rule for that paragraph wins.
A link inside that paragraph.Nothing selects it. Set an inherited property on ::slotted(p), and the link inherits it.Any rule for the link itself, even the browser's own blue for links.
Words placed straight in the slot.slot { color: seagreen; }. The words inherit from the slot.The component. The page can't select the slot or the words.

Why it matters: put the colors and fonts you want on the slot, or on the top-level elements, and let them flow down. A property that doesn't inherit, like a border on a list item, is the page's to set.

Why do page styles override ::slotted()?

Asha's card works. Then the menu page gets a new style sheet from the site's designer. It gives every heading margin: 2rem. The gap above the tea's name comes back:

The page's h3 rule against the card's ::slotted(h3) rulePop out in the code editor (opens in a new tab)HTML
<style>  h3 { margin: 2rem; }</style><tea-card>  <h3 slot="name">Green tea</h3></tea-card><script src="tea-card.js"></script><script>  const style = getComputedStyle(document.querySelector("h3"));  console.log("Margin:", style.marginTop, "Color:", style.color);</script>
ResultLoading…
  • Line 2 is the page's rule: every <h3> gets a 2rem margin. Here, 2rem is 32px.
  • Line 5 is the heading, in the name slot.
  • In the tea-card.js tab, line 7 sets the slotted heading's margin to 0 and its color to seagreen.
  • Back in the page, line 10 prints the heading's margin and color.

It prints Margin: 32px Color: rgb(46, 139, 87). The page won the margin. But the color is still the card's seagreen, because the page never set one.

It works one property at a time. Where the page has its own rule for a slotted element, the page wins. Where the page says nothing, ::slotted() fills in. Lesson 11.2 met the same thing with :host: the page's rule for the tag beat it.

Try five page rules:

Playground: which page rules beat ::slotted()?
A page rule, and a heading in the card's name slotPop out in the code editor (opens in a new tab)HTML
<style>  /* no rule */</style><tea-card>  <h3 slot="name">Green tea</h3></tea-card><script src="tea-card.js"></script><script>  const style = getComputedStyle(document.querySelector("h3"));  console.log("Margin:", style.marginTop, "Color:", style.color);</script>
ResultLoading…
Try it yourself
The card's rule applies.

Margin: 0px. Color: rgb(46, 139, 87). The page says nothing about the heading, so ::slotted(h3) sets both: no margin, and seagreen. It even beats the browser's own margin for headings.

The card stays the same: line 7 of the tea-card.js tab sets the heading's margin to 0 and its color to seagreen. Each choice changes only the page's rule on line 2.
  • No page rule: 0px and seagreen. The card's rule even beats the browser's own margin for headings.
  • h3 { margin: 2rem; }: 32px and seagreen.
  • :where(h3) { margin: 2rem; }: still 32px. :where() gives its selector a specificity of zero, lower than ::slotted(h3). The page still wins.
  • h3 { color: crimson; }: 0px and crimson. Now the page owns the color.
  • body { color: crimson; }: 0px and seagreen. This rule matches the body, not the heading.

Why doesn't specificity decide?

Specificity is the score CSS uses to choose between two rules for the same element. But the cascade compares other things first. One of them, in the CSS Cascade spec, is the context: which tree a rule comes from. A shadow root is its own context, inside the page's. For normal rules, the rule from the outer context wins. So the page beats the card before specificity is ever compared.

The spec gives the reason in a note. Rules inside a component set defaults, and the page outside can easily change them. The browser's own styles sit lower still, as lesson 11.2 showed. So a ::slotted() rule lands in the middle:

  • below any page rule that matches the same element;
  • above the browser's defaults, like a heading's margin.
Two properties of the slotted heading, each with three sources: the browser, the card's ::slotted(h3) rule, and the page. Margin: the browser's 18.72px and the card's 0 are crossed out, and the page's 2rem wins. Color: the browser and the page have no rule, and the card's seagreen applies.the browserthe card's ::slotted(h3)the pagemargin: 18.72pxmargin: 0margin: 2remthe page winsno rulecolor: seagreenno rulethe card's rule applies
For each property, the page's own rule wins. Where the page says nothing, the card's ::slotted() rule applies, and it still beats the browser's default.
Real-life analogyGift wrapping at the counter

Leaf and Kettle wraps every gift tin for free, in green paper with a white ribbon. If you bring your own paper, they use yours. If you didn't bring a ribbon, they still tie on theirs.

In real life: The shop's green paper and white ribbon
In JavaScript: The card's ::slotted() rule
In real life: The paper you brought
In JavaScript: A page rule for the same property, which wins
In real life: The ribbon you didn't bring
In JavaScript: A property the page leaves alone, which the card fills in
In real life: The plain tin as it came
In JavaScript: The browser's defaults, which both cover

One thing flips this order: !important. Lesson 11.4, The shadow cascade and which styles win, explains the whole order, and when that's fair to the page. Chrome's styling guide advises using ::slotted() for light touches, not for control.

Why it matters: write ::slotted() rules as defaults the page may change. The page's own styles for its content are the page's to set.

How do you style an empty slot with :has-slotted?

Asha's next card has a Tasting notes heading above its default slot. When the page gives no notes, the heading sits above nothing. Lesson 8.4 met :has-slotted: a pseudo-class that matches a slot with nodes assigned to it. It also showed two catches. Only Firefox has it, and a single space counts as content. Here is how you style with it.

:has-slotted matches the slot. But the heading is the slot's neighbor. So wrap both in a box, and ask about the box with :has(). :has() matches an element that holds something matching its argument.

Hiding the notes box with :has-slottedPop out in the code editor (opens in a new tab)HTML
<tea-card>  <p>Grassy and fresh.</p></tea-card><tea-card></tea-card><script src="tea-card.js"></script><script>  console.log(":has-slotted:", CSS.supports("selector(:has-slotted)"));  for (const card of document.querySelectorAll("tea-card")) {    const notes = card.shadowRoot.querySelector(".notes");    console.log("Notes box:", getComputedStyle(notes).display);  }</script>
ResultLoading…
  • Lines 1 to 3 of the page are a card with a note. Line 4 is an empty card.
  • In the tea-card.js tab, lines 9 to 12 are the notes box: the heading and the slot.
  • Line 7 hides a notes box that holds an empty slot. Read it from the inside out. slot:not(:has-slotted) is a slot with nothing assigned. .notes:has(...) is a box that holds one.
  • Back in the page, line 7 asks whether the browser knows :has-slotted, as lesson 8.4 did. Lines 8 to 11 print each card's notes box display.

In Chrome, it prints :has-slotted: false, then Notes box: block twice. The empty card shows a heading above nothing. Chrome doesn't support :has-slotted, so it drops line 7. Safari prints the same. In Firefox, it prints true, block, and none: the empty card's box is hidden.

Look at which way the rule points. It hides the box only when the browser can tell that the slot is empty. A browser without :has-slotted drops the rule and shows the heading, notes or not. Written the other way, hidden by default and shown by a :has-slotted rule, every card in Chrome would hide its notes.

Real-life analogyA tea tin with a window, or a label you write

Some tea tins have a little window, so anyone can see if there's tea inside. Even a few leaves at the bottom show. Most of Leaf and Kettle's tins are plain. So Ravi looks inside when he fills one, and writes Full on its label. Anyone can read the label from across the shop.

In real life: A tin with a little window
In JavaScript: :has-slotted, which the browser keeps up to date
In real life: A few leaves showing at the bottom
In JavaScript: One space, which counts as content
In real life: Writing Full on the label yourself
In JavaScript: The slotchange check setting has-notes
In real life: Reading the label from across the shop
In JavaScript: :host([has-notes]) in the card's CSS

Hiding the heading in every browser

Until the other browsers ship it, use the check from lesson 8.4. A slotchange listener looks at what's in the slot, and sets an attribute on the host. The CSS reads the attribute:

The slotchange check sets has-notes, and the CSS reads itPop out in the code editor (opens in a new tab)HTML
<tea-card>  <p>Grassy and fresh.</p></tea-card><tea-card></tea-card><script src="tea-card.js"></script><script>  console.log(":has-slotted:", CSS.supports("selector(:has-slotted)"));  for (const card of document.querySelectorAll("tea-card")) {    const notes = card.shadowRoot.querySelector(".notes");    console.log("Notes box:", getComputedStyle(notes).display);  }</script>
ResultLoading…
  • The page is the same as above. Only the file changed.
  • In the tea-card.js tab, line 7 hides the notes box unless the host has the has-notes attribute.
  • Lines 13 and 14 listen for slotchange on the slot. Line 15 is lesson 8.4's check: an element, or text with real words in it, counts as a note.
  • Line 16 adds has-notes to the host when there are notes, and removes it when there aren't.

In every browser, it prints Notes box: block and Notes box: none. The empty card fires no slotchange, so it never gets the attribute, and its box stays hidden. The check is stricter than :has-slotted too. A card with one space inside stays hidden here, while :has-slotted counts the space.

The kit's card has used the same check since lesson 8.4. Lesson 12.3, Custom states and :state(), covers custom states, which can do the same job: :host(:state(has-notes)).

Why it matters: point :has-slotted rules the safe way, and let the JavaScript check decide, as lesson 8.4 advised. Chrome Platform Status lists :has-slotted as behind a flag. And the spec expects a later version to offer a way to skip a slot that holds only spaces.

Fitting the page's notes into the tea card

Now the kit. Since lesson 8.1, the kit's card shows tasting notes in its default slot. A page usually writes a note as a paragraph. The card's own p rule styles its price line, but not the page's note. So the note keeps the browser's paragraph margins, 16px above and below, and sits loosely in the card.

This lesson's kit adds one line:

The kit card's styles (tea-kit/tea-card.js, lines 5 to 13)JavaScript
  <style>
    .card { border: 2px solid seagreen; border-radius: 8px; padding: 8px 12px; }
    h3 { margin: 0; color: seagreen; }
    p { margin: 4px 0 0; }
    h4 { margin: 8px 0 0; }
    .buy { display: flex; align-items: center; gap: 8px; margin-top: 8px; }
    button { font: inherit; }
    ::slotted(p) { margin: 4px 0 0; }
  </style>
  • Line 4 is the card's own rule, for its price line.
  • Line 8 is new. ::slotted(p) gives the page's paragraphs the same spacing.

Switch between the two kits. The page stays the same:

Playground: the kit card's notes, before and after
A kit card with a notePop out in the code editor (opens in a new tab)HTML
<tea-card name="Oolong" price="5">  <p>Floral, with a honey finish.</p></tea-card><script type="module">  import "./tea-kit/index.js";   const note = document.querySelector("tea-card p");  const style = getComputedStyle(note);  console.log("Note margins:", style.marginTop, style.marginBottom);</script>
ResultLoading…
Try it yourself
A loose note.

Note margins: 16px 16px. The card's own p rule can't reach the page's note. So the note keeps the browser's paragraph margins: 16px above and 16px below.

The page stays the same. Only the kit changes: open the tea-kit/tea-card.js tab to see the card's new line.
  • Lines 1 to 3 are a kit card with a note.
  • Line 5 loads the kit. Lines 7 to 9 print the note's top and bottom margins.

With the kit from lesson 11.2, it prints Note margins: 16px 16px. With this lesson's kit, it prints Note margins: 4px 0px. The note sits 4px under the Tasting notes heading, the same gap as the price under the name.

Two things from this lesson still hold. A page that wants more room writes its own rule, like tea-card p { margin: 12px 0 0; }, and its rule wins. And inside tea-panel, from lesson 8.3, a note reaches the card through the panel's slot. The card's rule still matches it. The spec says ::slotted() matches what's assigned after flattening, so the page's paragraph counts, not the panel's slot.

Common mix-ups

  • "A p rule in my shadow root styles the paragraphs the page puts in my slots." No. Selectors in a shadow root only match its own elements. Use ::slotted(p).
  • "::slotted() styles everything inside a slotted element." No. It matches only the top-level elements in a slot. What's inside them can only inherit.
  • "::slotted(div p) reaches the paragraph in the div." No. The space is a combinator, so the browser drops the whole rule.
  • "::slotted(*) styles the text in a slot." No. It never matches text. Style the slot, and let the text inherit.
  • "A more specific ::slotted() rule beats the page's rule." No. The page wins before specificity is compared.
  • "Any page style beats ::slotted()." No. Only a page rule that matches the element itself. A color the element would inherit from the page loses.
  • "::slotted(p):hover styles a note on hover." No. Browsers drop it. Write ::slotted(p:hover).
  • ":has-slotted works in every browser." No. Only Firefox ships it. Keep the slotchange check.

Practice exercises

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

Exercise 1 · Warm-upHow many turn seagreen?

The card's style is ::slotted(p) { color: seagreen; }. What does the console print?

<tea-card>  <p slot="name">Green tea</p>  <p>Grassy and fresh.</p>  <div><p>Brew for 2 minutes.</p></div></tea-card><script src="tea-card.js"></script><script>  const all = document.querySelectorAll("tea-card p");  const green = [...all].filter((p) => getComputedStyle(p).color === "rgb(46, 139, 87)");  console.log(green.length);</script>
ResultLoading…

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

    Exercise 2 · Warm-upInherited or the card's?

    The page colors the body crimson. The card colors its slotted paragraph seagreen. What does the console print?

    <style>  body { color: crimson; }</style><tea-card>  <p>Grassy and fresh.</p></tea-card><script src="tea-card.js"></script><script>  console.log(getComputedStyle(document.querySelector("p")).color);</script>
    ResultLoading…

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

      Exercise 3 · PracticeColor the list items

      The list items should be seagreen, but they stay black. Fix it in the tea-card.js tab. What does your fixed page print?

      <tea-card>  <ul>    <li>Grassy</li>    <li>Fresh</li>  </ul></tea-card><script src="tea-card.js"></script><script>  console.log(getComputedStyle(document.querySelector("li")).color);</script>
      ResultLoading…

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

        Exercise 4 · PracticeOnly the name heading

        Only the heading in the name slot should lose its margin. Change the card's rule. What does the Our pick line print after your fix?

        <tea-card>  <h3 slot="name">Green tea</h3>  <h3>Our pick</h3></tea-card><script src="tea-card.js"></script><script>  for (const h3 of document.querySelectorAll("h3")) {    console.log(h3.textContent, getComputedStyle(h3).marginTop);  }</script>
        ResultLoading…

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

          Exercise 5 · ChallengeA hover rule that never works

          The note should turn seagreen on hover, but it never does. Find the bug and fix it. What does your fixed page print?

          <tea-card>  <p>Grassy and fresh.</p></tea-card><script src="tea-card.js"></script><script>  const style = document.querySelector("tea-card").shadowRoot.querySelector("style");  console.log(style.sheet.cssRules.length);</script>
          ResultLoading…

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

            Exercise 6 · ChallengeHide empty notes in every browser

            This card hides empty notes only in Firefox. Make it work in every browser. What does the empty card's line print after your fix?

            <tea-card>  <p>Grassy and fresh.</p></tea-card><tea-card></tea-card><script src="tea-card.js"></script><script>  console.log(":has-slotted:", CSS.supports("selector(:has-slotted)"));  for (const card of document.querySelectorAll("tea-card")) {    const notes = card.shadowRoot.querySelector(".notes");    console.log("Notes box:", getComputedStyle(notes).display);  }</script>
            ResultLoading…

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

              Check your understanding

              For each question, ask yourself: is this element at the top of a slot, and does the page have its own rule for it?

              The styling slotted content quiz · 7 questionsScore: first tries count
              1. Question 1 of 7Inside the tea card's shadow root, which rule styles a <p> the page put in one of the card's slots?

                Choose an answer to see the explanation.

              2. Question 2 of 7What does this page print, with a page rule for every p and a more specific ::slotted() rule inside?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <style>
                  p { color: darkorange; }
                </style>
                <tea-card><p class="note">Grassy</p></tea-card>
                <script>
                  const card = document.querySelector("tea-card");
                  const root = card.attachShadow({ mode: "open" });
                  root.innerHTML = "<style>::slotted(p.note) { color: seagreen; }</style><slot></slot>";
                  console.log(getComputedStyle(card.querySelector("p")).color);
                </script>

                Choose an answer to see the explanation.

              3. Question 3 of 7A slotted <div> holds a <p>. What can ::slotted(div) do for that <p>?

                Choose an answer to see the explanation.

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

                Choose an answer to see the explanation.

              5. Question 5 of 7The page writes the words Fresh today straight into a card's slot. How can the card style them?

                Choose an answer to see the explanation.

              6. Question 6 of 7The page has body { color: crimson; }, and the card has ::slotted(p) { color: seagreen; }. What color is the slotted <p>?

                Choose an answer to see the explanation.

              7. Question 7 of 7Which browsers support :has-slotted?

                Choose an answer to see the explanation.

              Key takeaways

              • ::slotted(selector) in a shadow root's styles matches the elements the page put in its slots. On the page, it matches nothing.
              • The brackets take one compound selector. ::slotted(p span), ::slotted(p, ul), and ::slotted(p):hover are dropped.
              • Put a slot selector in front to pick one slot: slot[name="name"]::slotted(h3).
              • It matches only top-level elements: never text, and never the elements inside them. Reach those with inherited properties, on the slot or on ::slotted().
              • The page's own rules for a slotted element win, whatever their specificity. ::slotted() fills in where the page says nothing, and it beats the browser's defaults.
              • :has-slotted can style an empty slot, but only Firefox has it. Keep the slotchange check, and point :has-slotted rules so a browser without it still shows the content.

              Remember the one-liner.
              ::slotted() is a light touch: style the elements the page hands you, let the rest inherit, and let the page have the last word.

              Sources

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

              Coming next: The shadow cascade and which styles win. It explains the whole order between page and component styles, !important included.

              CompleteFrontend Clear concepts. Working examples.