completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Styling parts with ::part and exportparts

Learn how CSS ::part styles named elements inside a web component's shadow DOM, which selectors can follow it, and how exportparts passes parts up.

By the end, you can
  • 01
    Name parts and style themGive inner elements part names, and style them from the page with ::part(), :hover, and ::before.
  • 02
    Pass parts up through nested componentsForward a nested component's parts with exportparts, rename them, and find the level that forgot.
  • 03
    Design a small set of partsName parts by their job, document them with @csspart, and choose between a part and a custom property.

What are CSS shadow parts?

Meena's autumn menu is nearly done. The tea cards are wheat, with sienna borders, from lesson 12.1's custom properties. One thing still looks wrong. The Add button is a plain button. Every other button on Leaf and Kettle's site is round and sienna, with white text.

She writes tea-card button { background: sienna; }. Nothing changes. Page selectors stop at a shadow root, as lesson 6.3 showed. Ravi, who builds the kit, could add a custom property for the color. Then one for the text, one for the corners, and more for hover. That list never ends. So he names the button as a part. What does that do?

A web component lets a page style an element in its shadow root when the element has a part name, like <button part="add">. The page styles it with tea-card::part(add) and any CSS property. A part is seen only one level up, so a component inside another needs exportparts to pass its parts on.

In lesson 2.1 and lesson 2.3, you styled Web Awesome's parts from a page. Now you're the author. You decide which elements get a name. Here is a small card with one part:

A card with one part, and a page that styles itPop out in the code editor (opens in a new tab)HTML
<style>  tea-card::part(add) {    background: sienna;    color: white;    border-radius: 16px;  }</style><tea-card>Green tea</tea-card> <script src="tea-card.js"></script><script>  const add = document.querySelector("tea-card").shadowRoot.querySelector("button");  console.log("Add button:", getComputedStyle(add).backgroundColor);</script>
ResultLoading…
  • In the tea-card.js tab, line 6 is the card's own rule for its button. It's white, with a sea green border.
  • Line 9 is the button. part="add" gives it the part name add.
  • Back on the page, lines 2 to 6 style the card's add part. It gets a sienna background, white text, and round corners. Line 8 is the card.
  • Line 12 finds the button inside the card's shadow root. Line 13 prints its background with getComputedStyle(), which gives the value the browser really uses.

It prints Add button: rgb(160, 82, 45). That's sienna. The page's rule reached into the shadow root, but only to the element the card named. Press Edit & run and change line 2 to tea-card button {, Meena's first try. It prints Add button: rgb(255, 255, 255), the card's own white.

Real-life analogyHandles on a sealed tea tin

Leaf and Kettle sells its best tea in sealed tins. The maker fixed two handles on the outside and labelled them: lid and scoop. You can grip a handle, turn it, and even paint it. You can't reach the leaves inside. Only the handles the maker added are yours to hold.

In real life: The sealed tin
In CSS: The card's shadow root
In real life: The tin's maker
In CSS: The component's author, Ravi
In real life: A handle with a label
In CSS: An element with a part name, part="add"
In real life: Gripping a handle by its label
In CSS: tea-card::part(add) in the page's CSS
In real life: The tea leaves inside
In CSS: Every element with no part name
The main idea

A part is an element in a shadow root that the component names with the part attribute. The page styles it with ::part() and any CSS property. Elements with no part name stay private.

Every current browser supports parts. They're Baseline widely available.

What does the part attribute do?

The part attribute holds a list of part names, separated by spaces, like class. A part name is a word the page can put inside ::part(). The CSS Shadow spec says to think of it as a class, not an id or a tag name. So:

  • one element can have several names;
  • several elements can share one name.

Ravi tries it on the quantity from lesson 9.2 first, on a page of its own. Its two buttons share the name button. Each one also has a name of its own. Pick what goes inside ::part():

Playground: which elements does the selector style?
One ::part() rule and the quantity's three partsPop out in the code editor (opens in a new tab)HTML
<style>  tea-quantity::part(button) { background: wheat; }</style><tea-quantity></tea-quantity> <script src="tea-quantity.js"></script><script>  const names = { "rgb(245, 222, 179)": "wheat", "rgb(160, 82, 45)": "sienna", "rgb(230, 230, 250)": "lavender" };  for (const part of document.querySelector("tea-quantity").shadowRoot.children) {    const color = getComputedStyle(part).backgroundColor;    console.log(`${part.getAttribute("part")}:`, names[color] ?? "plain");  }</script>
ResultLoading…
Try it yourself
One name, two elements

It prints button less: wheat, number: plain, button more: wheat. Both buttons have the name button, so one rule styles both, the way a class would. The number has another name.

Only line 2 changes: the names inside ::part(). The tea-quantity.js tab names the buttons button less and button more, and the number number.
  • In the tea-quantity.js tab, lines 5 to 7 are the quantity's three elements. Line 5 is the - button, with two names: button and less. Line 7 is the + button: button and more. Line 6 is the number, called number.
  • On the page, line 2 is the only line that changes. It gives matching parts a wheat background.
  • Line 8 turns Chrome's color values back into names. Lines 9 to 12 print each part's names and its color.

With button, both buttons turn wheat. less and button less pick only the - button. With two names in the brackets, an element needs both. less more and Button style nothing. Part names are case-sensitive, so a capital B makes another name.

On the left, the page's rule, tea-quantity::part(button), with the note styles both buttons. On the right, a window labelled shadow root holds three cards: part button less, part number, and part button more. Arrows go from the rule to the two button cards. The number card is faded.The pagetea-quantity::part(button)styles both buttonsshadow rootpart="button less"part="number"part="button more"
Part names work like classes. Both buttons have the name button, so ::part(button) styles both. The number has only the name number, so it stays as it was.

Why it matters: a shared name lets a page style a group with one rule. A name of its own lets it style one element.

Reading part names from JavaScript

An element's part property gives its names as a DOMTokenList. That's the same kind of list that classList gives for classes. It has add(), remove(), toggle(), and contains().

Reading and changing a part's namesPop out in the code editor (opens in a new tab)HTML
<tea-quantity></tea-quantity> <script src="tea-quantity.js"></script><script>  const less = document.querySelector("tea-quantity").shadowRoot.querySelector("button");  console.log(less.part.value);  console.log(less.part.contains("less"));  less.part.add("minimum");  console.log(less.getAttribute("part"));</script>
ResultLoading…
  • Line 5 finds the - button inside the quantity's shadow root.
  • Line 6 prints less.part.value, the whole list as text: button less.
  • Line 7 asks if less is one of its names. It prints true.
  • Line 8 adds a third name, minimum. Line 9 reads the attribute again. It prints button less minimum.

The list and the attribute stay in step. So a component can add a name while something is true. MDN's tabs example names the open tab tab active this way. Lesson 12.3 shows custom states, which often fit that job better.

One more thing before you add names: each one is a promise. Once a page writes tea-card::part(add), renaming add breaks that page. The section on choosing names comes back to this.

How does ::part() style a part from outside?

::part() is a pseudo-element: a selector for a piece of an element, like ::before. First write a selector for the host, then ::part() with the names. The host lives in the page's own tree, so any page selector works before it. .autumn tea-card::part(add) styles the cards in the autumn section. tea-card:hover::part(add) styles the button while the pointer is over the card. Parts work the same in a closed shadow root, as lesson 6.2 noted.

When the card styles the same part

The card has its own rule for the button, and so does the page. Which one wins? Lesson 11.4 answered this for :host. A page and a shadow root are two contexts. For normal rules, the outer context wins: the page. For !important rules, the inner one wins. A ::part() rule belongs to the page's context. Try three rules in the card:

Playground: the card's rule against the page's
A page's ::part() rule and the card's own rule for the same buttonPop out in the code editor (opens in a new tab)HTML
<style>  tea-card::part(add) { background: sienna; }</style><tea-card>Green tea</tea-card> <script>  class TeaCard extends HTMLElement {    constructor() {      super();      this.attachShadow({ mode: "open" }).innerHTML = `        <style>button { background: white; }</style>        <h3><slot></slot></h3>        <button id="add" part="add">Add 1</button>`;    }  }  customElements.define("tea-card", TeaCard);   const add = document.querySelector("tea-card").shadowRoot.querySelector("button");  console.log("Add button:", getComputedStyle(add).backgroundColor);</script>
ResultLoading…
Try it yourself
The page's rule wins

It prints Add button: rgb(160, 82, 45). Both rules are normal, so the outer context wins: the page. The button is sienna.

Only line 11 changes: the card's own rule for its button, inside its shadow root. The page's rule on line 2 stays sienna.
  • Line 2 is the page's rule. It makes the add part sienna.
  • Line 11 is the only line that changes. It's the card's own rule, inside its shadow root.
  • Lines 18 and 19 print the button's background.

With button and #add, it prints Add button: rgb(160, 82, 45). The id doesn't help, because specificity only compares rules in one context. With !important, it prints Add button: rgb(255, 255, 255). Chrome's article on CSS names gives the same order. The shadow root's style comes first. The page's ::part() rule comes next. The shadow root's !important rules come last.

Why it matters: what the card writes for a part is only a default. Keep !important for the few things a page must never change.

Only the host's own shadow tree

tea-card::part() looks in one place: the card's own shadow tree. In the kit, the quantity sits inside the card's shadow root, and it has a shadow root of its own. Its buttons are parts of the quantity, not of the card. Meena tries two rules:

Two page rules that don't reach a part one level further inPop out in the code editor (opens in a new tab)HTML
<style>  tea-card::part(button) { background: wheat; }  tea-quantity::part(button) { background: wheat; }</style><tea-card></tea-card> <script src="tea-quantity.js"></script><script>  class TeaCard extends HTMLElement {    constructor() {      super();      this.attachShadow({ mode: "open" }).innerHTML = `        <tea-quantity></tea-quantity>`;    }  }  customElements.define("tea-card", TeaCard);   const card = document.querySelector("tea-card").shadowRoot;  const less = card.querySelector("tea-quantity").shadowRoot.querySelector("button");  const wheat = getComputedStyle(less).backgroundColor === "rgb(245, 222, 179)";  console.log("Minus button:", wheat ? "wheat" : "plain");</script>
ResultLoading…
  • Line 2 asks the card for a part named button. The card has none.
  • Line 3 asks for the quantity's part. But the page's tea-quantity selector can't find a quantity inside the card's shadow root.
  • Lines 9 to 16 are the card, with the quantity on line 13. Lines 18 to 21 print the - button's color.

It prints Minus button: plain. Neither rule reached it. A part is seen only by the tree that holds its host, here the card's shadow root. So the card itself can style it. Change line 13 to <style>tea-quantity::part(button) { background: wheat; }</style><tea-quantity></tea-quantity>`; and run it. It prints Minus button: wheat. To let the page do it, the card has to pass the part on, with exportparts.

Which pseudo-classes work with ::part()?

A pseudo-class is a selector for a state, like :hover. Some may follow ::part(), and some may not. MDN's page on ::part() gives the rule. A pseudo-class about the part itself may follow it. One that looks at the tree around it may not. Pseudo-elements like ::before may follow too. Try five:

Playground: what can follow ::part()?
One rule after ::part(), and how many rules the browser keptPop out in the code editor (opens in a new tab)HTML
<style>  tea-quantity::part(button):hover { background: wheat; }</style><tea-quantity></tea-quantity> <script src="tea-quantity.js"></script><script>  const sheet = document.querySelector("style").sheet;  console.log("Rules kept:", sheet.cssRules.length);</script>
ResultLoading…
Try it yourself
Kept: the reader's pointer

It prints Rules kept: 1. Move the pointer over - or + in the result. The button under it turns wheat.

Only line 2 changes. Lines 8 and 9 count the rules the browser kept from the page's style sheet.
  • Line 2 is the only line that changes.
  • Line 8 gets the page's style sheet. Line 9 prints how many rules the browser kept from it.

:hover, :focus-visible, and ::before print Rules kept: 1. Each one works in the result too. :last-child and :empty print Rules kept: 0. Chrome doesn't keep a rule that could never match. Its selector isn't valid, so the rule is thrown away as soon as it's read.

Why it matters: a dropped rule leaves no error in the console. If a part rule does nothing, check what follows the brackets.

Here is what Chrome does with each kind of selector after ::part(button). Read each row across:

What can follow ::part()?
What follows ::part(button)Does Chrome keep the rule?Why
:hover, :focus, :focus-visible, :activeYes.They ask what the reader is doing to the part right now.
:disabled, :enabled, :checkedYes.They ask about the part's own state.
:state(busy)Yes.It asks about a custom state of the part, when the part is a custom element.
::before, ::after, ::first-letter, ::placeholderYes.They style a piece of the part itself.
:first-child, :last-child, :nth-child(2), :only-childNo. It drops the whole rule.They ask where the part sits among the elements around it.
:empty, :has(span)No. It drops the whole rule.They ask what is inside the part.
A space, >, or +, as in ::part(button) spanNo. It drops the whole rule.They would walk from the part to other elements in the shadow tree.
A second ::part(), as in ::part(button)::part(label)No. It drops the whole rule.A part of a part reaches the page only through exportparts.

:state() is in the table because a part can be a custom element. If the card named its quantity quantity, and the quantity had a busy state, tea-card::part(quantity):state(busy) would match it. The next lesson covers custom states.

A page can restyle a part's focus ring with :focus-visible, and Accessible components covers how to keep it easy to see.

How does exportparts pass parts up from a nested component?

Back to the kit. The quantity sits in the card's shadow root, and its buttons are its own parts. To let the page style them, the card puts exportparts on the quantity. The exportparts attribute goes on a host inside a shadow root. It lists parts of that host to expose as parts of the component around it. MDN calls this exporting. Pick what the card forwards:

Playground: what the card forwards
A card that holds a quantity, and three page rules for its partsPop out in the code editor (opens in a new tab)HTML
<style>  tea-card::part(button) { background: wheat; }  tea-card::part(quantity-button) { background: sienna; }  tea-card::part(quantity-number) { background: lavender; }</style><tea-card></tea-card> <script src="tea-quantity.js"></script><script>  class TeaCard extends HTMLElement {    constructor() {      super();      this.attachShadow({ mode: "open" }).innerHTML = `        <tea-quantity></tea-quantity>`;    }  }  customElements.define("tea-card", TeaCard);   const names = { "rgb(245, 222, 179)": "wheat", "rgb(160, 82, 45)": "sienna", "rgb(230, 230, 250)": "lavender" };  const quantity = document.querySelector("tea-card").shadowRoot.querySelector("tea-quantity");  for (const part of quantity.shadowRoot.children) {    const color = getComputedStyle(part).backgroundColor;    console.log(`${part.getAttribute("part")}:`, names[color] ?? "plain");  }</script>
ResultLoading…
Try it yourself
Nothing reaches the page

It prints button less: plain, number: plain, button more: plain. The quantity's parts belong to the card's shadow root. The card passes none of them on, so no page rule matches.

Only line 14 changes: the exportparts attribute on the quantity inside the card. The page's three rules stay the same.
  • Lines 2 to 4 are three page rules, for three names: button, quantity-button, and quantity-number.
  • Line 14 is the only line that changes. It's the quantity, inside the card's shadow root.
  • Lines 19 to 24 print each of the quantity's parts and its color.

With No exportparts, every part is plain. With button, the buttons turn wheat: the card forwards the part under the same name. With button: quantity-button, they turn sienna, and line 2 stops matching. With Two parts, the number turns lavender too.

So exportparts is a list of mappings, separated by commas. Each mapping is one of these:

  • button forwards the part under the same name. It's short for button: button.
  • button: quantity-button forwards the inner part button under the outer name quantity-button. Only the outer name works from the page.

To expose both names, list both: exportparts="button, button: quantity-button". The spec allows one inner part under several names.

A column of the page's rule and three windows, from the outside in. At the top, the page's rule tea-panel::part(quantity-button). Below it, a tea-panel window holds exportparts equals quantity-button, noted passes it on. Below that, a tea-card window holds exportparts equals button: quantity-button, noted renames button. At the bottom, a tea-quantity window holds button part equals button less, noted names it button. Arrows point up from each window to the one above.tea-panel::part(quantity-button)the page's ruletea-panelexportparts="quantity-button"passes it ontea-cardexportparts="button: quantity-button"renames buttontea-quantity<button part="button less">names it button
The quantity names its buttons button. The card forwards that part as quantity-button, and the panel forwards quantity-button again. Each level sees only the level just inside it, so all three steps are needed.

Why rename a forwarded part?

A forwarded name joins the card's own names. Say the card had its own button part, and forwarded the quantity's button too. Then tea-card::part(button) would style all three buttons at once. A prefix says whose part it is: quantity-button belongs to the quantity. Web Awesome's dialog does the same with close-button__button, as lesson 2.3 showed.

Real-life analogyCopying a line onto the café's phone list

Leaf and Kettle's front desk keeps a phone list of the café's staff. The warehouse next door has its own list, and Ravi's packing room is on it. A caller at the front desk can only ask for names on the café's list. So the café copies that line, as "Warehouse packing". If the warehouse never listed the room, the café has nothing to copy.

In real life: The café's phone list
In HTML: The parts a page can reach on the outer component
In real life: The warehouse's own list
In HTML: The parts of the component inside it
In real life: Copying a line, under a new heading
In HTML: exportparts="button: quantity-button"
In real life: A room the warehouse never listed
In HTML: A part the middle component never forwarded

Every level must forward

In the kit, the quantity sits two levels down inside the panel from lesson 8.3: the panel holds the card, and the card holds the quantity. A page rule on the panel needs every level in between to forward the part. The spec builds each shadow root's list of parts from the level just inside it, one level at a time. Pick who forwards:

Playground: who forwards the buttons?
A panel that holds a card that holds a quantityPop out in the code editor (opens in a new tab)HTML
<style>  tea-panel::part(quantity-button) { background: sienna; }</style><tea-panel></tea-panel> <script src="tea-quantity.js"></script><script>  class TeaCard extends HTMLElement {    constructor() {      super();      this.attachShadow({ mode: "open" }).innerHTML = `        <tea-quantity exportparts="button: quantity-button"></tea-quantity>`;    }  }  class TeaPanel extends HTMLElement {    constructor() {      super();      this.attachShadow({ mode: "open" }).innerHTML = `        <tea-card exportparts="quantity-button"></tea-card>`;    }  }  customElements.define("tea-card", TeaCard);  customElements.define("tea-panel", TeaPanel);   const card = document.querySelector("tea-panel").shadowRoot.querySelector("tea-card");  const less = card.shadowRoot.querySelector("tea-quantity").shadowRoot.querySelector("button");  const sienna = getComputedStyle(less).backgroundColor === "rgb(160, 82, 45)";  console.log("Minus button:", sienna ? "sienna" : "plain");</script>
ResultLoading…
Try it yourself
Passed up two levels

It prints Minus button: sienna. The card forwards button as quantity-button, and the panel forwards quantity-button. Line 2 reaches the quantity's buttons.

Only lines 12 and 19 change: the card's exportparts and the panel's. The page's rule on line 2 stays the same.
  • Line 2 styles the panel's quantity-button part.
  • Line 12 is the quantity, inside the card's shadow root. Line 19 is the card, inside the panel's.
  • Lines 25 to 28 find the - button, three shadow roots down, and print its color.

Only Both forward prints Minus button: sienna. With Only the panel, the panel lists quantity-button, but the card never made one. Nothing tells you. MDN's nested card example shows the same thing: its footer part isn't in exportparts, so the page can't style it. Forget exportparts at any level, and the part is invisible to the page.

What can't ::part() style?

A part opens one element, on purpose. The CSS Shadow spec says why. The old >>> selector showed too much of a component's inside, and browsers dropped it. A part shows only what the author chose. So a ::part() rule can't:

  • select elements inside the part, like ::part(price) strong;
  • ask where the part sits, with :first-child or :nth-child();
  • reach a part of a part, like ::part(card)::part(button), unless each level forwards it;
  • use names declared inside the shadow root, in Chrome.

The first one surprises people most. Ravi puts the number of the price line in a <strong>:

A rule for the part, and a rule that walks into itPop out in the code editor (opens in a new tab)HTML
<style>  tea-card::part(price) { color: sienna; border-bottom: 2px solid sienna; }  tea-card::part(price) strong { color: crimson; }</style><tea-card></tea-card> <script>  class TeaCard extends HTMLElement {    constructor() {      super();      this.attachShadow({ mode: "open" }).innerHTML = `        <p part="price">Price: <strong>4</strong></p>`;    }  }  customElements.define("tea-card", TeaCard);   const strong = document.querySelector("tea-card").shadowRoot.querySelector("strong");  console.log("Rules kept:", document.querySelector("style").sheet.cssRules.length);  console.log("Number color:", getComputedStyle(strong).color);  console.log("Number border:", getComputedStyle(strong).borderBottomWidth);</script>
ResultLoading…
  • Line 12 is the price part. The number sits in a <strong> inside it.
  • Line 2 styles the part: sienna text and a sienna line under it.
  • Line 3 tries to make the <strong> crimson.
  • Line 18 counts the rules the browser kept. Lines 19 and 20 print the number's color and border.

It prints Rules kept: 1, Number color: rgb(160, 82, 45), and Number border: 0px. Line 3 was dropped. The number still turned sienna, because color is inherited: the <strong> takes it from the part. A border isn't inherited, so it stays on the part. Text the page puts in a slot inside a part inherits the same way.

On the left, two page rules. tea-card::part(price) has an arrow to a card p part equals price inside a tea-card window. tea-card::part(price) strong is faded and crossed out, labelled dropped. Inside the window, an arrow labelled inherits color goes from the p card down to a strong card, with the notes sienna text and no border.The page's rulestea-card::part(price)tea-card::part(price) strongdroppedtea-card<p part="price">inherits color<strong>sienna textno border
::part(price) styles the <p> itself. Its color is inherited, so the <strong> inside turns sienna too, but the border stays on the part. A selector that walks into the part is dropped.
Real-life analogyAsking the waiter

At Leaf and Kettle, you talk to your waiter, Asha. You can ask her for a red cloth on your table. You can't call a cook in the kitchen by name. But if you ask for less sugar, Asha passes it on, and the kitchen follows it.

In real life: Asha, the waiter you talk to
In CSS: The part, ::part(price)
In real life: The red cloth on your table
In CSS: A property on the part itself, like border-bottom
In real life: Calling a cook by name
In CSS: ::part(price) strong, which is dropped
In real life: "Less sugar", passed to the kitchen
In CSS: An inherited property, like color, that the part's children take

Names follow the same rule. A ::part() rule belongs to the page, so in Chrome it can only use names the page declares, like a page's @keyframes. Chrome's article on CSS names notes that Firefox also lets it use names from inside the shadow root, like keyframes and container names.

How do you choose and document part names?

Every part name is public. Cory LaViska, who created Shoelace, puts it plainly: every part you expose is an API you commit to supporting. Lesson 5.4 said the same about attributes and events. Renaming one breaks pages. So choose names with care:

  • Name the job, not the tag. Use name, not h3. If the card changes its heading to <h2>, name is still true.
  • Name the job, not the look. Use add, not sienna-button. A page may make it green.
  • Expose a few. Chrome's styling guide says to expose a few high-level parts, like a button, an input, or a label, not every <div>.
  • Give a group one shared name, and each member its own. Both quantity buttons are button, and each one is less or more.
  • Prefix a forwarded name. quantity-button says whose button it is.
  • Use lowercase words and hyphens. Part names are case-sensitive.

button isn't a tag name here. It names what the reader does: press it. Chrome's guide lists button among good part names.

How Web Awesome names its parts

Web Awesome's Number Input is a number between two buttons, like the quantity. Its docs list its parts in a table. Here are six of them. Read each row across:

Six of Web Awesome's Number Input parts
PartWhat it styles
number-inputThe outer wrapper around the whole control.
inputThe native <input> inside it.
stepperBoth stepper buttons, so one rule styles them together.
stepper-decrementThe - button on its own.
stepper-incrementThe + button on its own.
baseThe old name for the wrapper. It still works, and the docs mark it deprecated.

It follows the same pattern. stepper names both buttons, "for shared styling", the docs say. stepper-decrement and stepper-increment name each one. Every name says what its element does. And base shows how a library renames a part without breaking pages. The old name stays, marked deprecated. Its Button does the same: its base part points you to button.

Real-life analogyDishes on the printed menu

Leaf and Kettle prints its menu once a year. Customers order by the names on it. The kitchen may change a recipe any day. But a dish on the menu has to stay until the next printing. So the owner keeps the menu short.

In real life: A dish on the printed menu
In HTML: A part name in the component's docs
In real life: Changing a recipe in the kitchen
In HTML: Changing the markup inside the shadow root
In real life: Taking a dish off before the next printing
In HTML: Renaming a part before the next major version
In real life: A short menu
In HTML: A few parts, chosen on purpose

Documenting parts with @csspart

List every part in the component's JSDoc with @csspart, the way lesson 12.1 listed custom properties with @cssprop. The analyzer's docs say it can't find parts on its own, so it needs these lines. Here is the kit card's JSDoc after this lesson, shortened to its parts:

tea-card.js's JSDoc, shortened to its partsJavaScript
/**
 * A tea card: a tea's name and price in a box, with a quantity and an Add button. Its own shadow root holds them.
 *
 * @tag tea-card
 * @csspart name - The tea's name.
 * @csspart price - The price line.
 * @csspart add - The Add button.
 * @csspart quantity-button - The quantity's - and + buttons: tea-quantity's button part, forwarded.
 */
  • Line 4 names the tag.
  • Lines 5 to 8 each describe one part: its name, a dash, and what it is.
  • Line 8 is the forwarded part. It says where the part comes from.

The analyzer turns those lines into the cssParts list of the card's entry in custom-elements.json. The kit writes its manifest by hand, to match:

The cssParts list in the kit's custom-elements.jsonJSON
"cssParts": [
  {
    "name": "name",
    "description": "The tea's name."
  },
  {
    "name": "price",
    "description": "The price line."
  },
  {
    "name": "add",
    "description": "The Add button."
  },
  {
    "name": "quantity-button",
    "description": "The quantity's - and + buttons: tea-quantity's button part, forwarded."
  }
]
  • Line 1 starts the list. Lines 2 to 5 are the name part, with its name and its description.
  • Lines 14 to 17 are the forwarded quantity-button.

The manifest's schema also has a deprecated field for a part. That's where a renamed part's old name goes, the way Web Awesome marks base.

Should you use a part or a custom property?

Lesson 12.1 gave the card three custom properties. Now it has parts too. They do different jobs. Chrome's styling guide puts it in one line. Use custom properties for "a constrained, design-system-safe set of values". Use parts for "unrestricted styling of a specific element".

Two halves. On the left, a custom property: a card --tea-card-bg: wheat with an arrow down to background: var(--_bg), noted one value, where the card reads it. On the right, a part: a card tea-card::part(add) with an arrow down to button part equals add, noted any property, any state.A custom property--tea-card-bg: wheatbackground: var(--_bg)one value, where the card reads itA parttea-card::part(add)<button part="add">any property, any state
A custom property passes one value in, and the card decides where it goes. A part opens one element to the page's own rules: any property, and states like :hover.
  • A custom property is one value the component chose to read, like a tap on lesson 12.1's shop wall. It reaches every level by inheritance. One line on body sets every card, even the one inside the panel.
  • A part opens one element to the page's own rules: any property, and states like :hover. It reaches only as far as each level forwards it.

The CSS Shadow spec explains why parts exist at all. With custom properties alone, a component that allowed any style would need hundreds of them, one for each CSS property. And each state, like :hover, would need its own set again.

The two can meet on one element. A page's ::part() rule beats the card's own rule. So tea-card::part(name) { color: crimson; } wins over --tea-card-accent for the tea's name, and the border keeps the accent. A good kit offers both: custom properties for the theme, and parts for the rest. Sort these requests:

Part or custom property?
  • The background of every card on the page
  • One corner radius for every kit component
  • The accent color of the card's border and its name, together
  • A soft shadow under the Add button
  • The Add button's look while the pointer is over it
  • Round quantity buttons
Try it yourself
0 of 6 correct

Put each request where it fits best in the tea kit's styling API.

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

Giving the tea kit a set of parts

Now the kit. Three files get parts:

  • tea-quantity names its buttons button, less, and more, and its number number.
  • tea-card names the tea's name name, the price line price, and the Add button add. It forwards the quantity's button as quantity-button.
  • tea-panel names its label label, and forwards the card's four parts under the same names.

The card's box gets no part. Its three custom properties cover what pages ask for, and the kit can change the box later without breaking anyone. Meena's autumn menu uses the new parts:

The kit's parts on the autumn menuPop out in the code editor (opens in a new tab)HTML
<style>  .autumn { --tea-card-bg: wheat; --tea-card-accent: sienna; }  :is(tea-card, tea-panel)::part(add) { background: sienna; color: white; border: 0; border-radius: 16px; }  :is(tea-card, tea-panel)::part(add):hover { background: saddlebrown; }  :is(tea-card, tea-panel)::part(quantity-button) { border-radius: 50%; }  tea-panel::part(label) { font-style: italic; }</style><section class="autumn">  <tea-card name="Oolong" price="5"></tea-card>  <tea-panel><span slot="heading">Black tea</span></tea-panel></section> <script type="module">  import "./tea-kit/index.js";  const inPanel = document.querySelector("tea-panel").shadowRoot.querySelector("tea-card");  for (const card of [document.querySelector("tea-card"), inPanel]) {    const add = card.shadowRoot.getElementById("add");    const less = card.shadowRoot.querySelector("tea-quantity").shadowRoot.getElementById("less");    console.log(getComputedStyle(add).backgroundColor, getComputedStyle(less).borderTopLeftRadius);  }</script>
ResultLoading…
  • In the tea-kit/tea-card.js tab, lines 22 and 23 name the heading name and the price line price. Line 27 forwards the quantity's buttons. Line 28 names the Add button add.
  • In the tea-kit/tea-panel.js tab, line 10 names the label. Line 11 forwards the card's four parts.
  • On the page, line 2 sets the autumn colors from lesson 12.1. Line 3 styles the add part of the card and the panel. :is(tea-card, tea-panel) matches either tag, so one rule serves both.
  • Line 4 darkens the button while the pointer is over it. Line 5 rounds the quantity's buttons. Line 6 puts the panel's label in italics.
  • Lines 15 to 20 find each card, the one inside the panel too. They print its Add button's background and its - button's corners.

It prints rgb(160, 82, 45) 50% twice. The card inside the panel got the same styles, through two levels of exportparts. Move the pointer over an Add button, and it turns a darker brown.

The kit's JSDoc and manifest now list every part. A page that writes no ::part() rule sees the same cards as before.

Common mix-ups

  • "A part opens the whole shadow root to the page." No. It opens one element. Its children, its neighbors, and their structure stay private.
  • "::part() reaches parts at any depth." No. It sees one level. Every component in between must forward the part with exportparts.
  • "exportparts="button: quantity-button" forwards both names." No. Only the new one. Write button, button: quantity-button to keep both.
  • "A rule like ::part(button):first-child just waits to match." No. Chrome drops the whole rule, as it does for ::part(button) span.
  • "You can't put ::before or ::after on a part." No. tea-quantity::part(number)::before adds text before the number.
  • "A more specific rule in the component beats the page's ::part() rule." No. The page wins for normal rules, even against an id. Only the component's !important wins.
  • "Part names ignore case, like HTML tags." No. ::part(Button) doesn't match part="button".

Practice exercises

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

Exercise 1 · Warm-upTwo names in the brackets

Line 2 styles tea-quantity::part(button more). Which button turns wheat?

<style>  tea-quantity::part(button more) { background: wheat; }</style><tea-quantity></tea-quantity> <script src="tea-quantity.js"></script><script>  const names = { "rgb(245, 222, 179)": "wheat", "rgb(160, 82, 45)": "sienna", "rgb(230, 230, 250)": "lavender" };  for (const part of document.querySelector("tea-quantity").shadowRoot.children) {    const color = getComputedStyle(part).backgroundColor;    console.log(`${part.getAttribute("part")}:`, names[color] ?? "plain");  }</script>
ResultLoading…

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

    Exercise 2 · Warm-upThe old name after a rename

    The card forwards the quantity's buttons, and the page styles tea-card::part(button). What does the page print?

    <style>  tea-card::part(button) { background: wheat; }</style><tea-card></tea-card> <script src="tea-quantity.js"></script><script>  class TeaCard extends HTMLElement {    constructor() {      super();      this.attachShadow({ mode: "open" }).innerHTML = `        <tea-quantity exportparts="button: quantity-button"></tea-quantity>`;    }  }  customElements.define("tea-card", TeaCard);   const quantity = document.querySelector("tea-card").shadowRoot.querySelector("tea-quantity");  const buttons = [...quantity.shadowRoot.querySelectorAll("button")];  const wheat = buttons.filter((button) => getComputedStyle(button).backgroundColor === "rgb(245, 222, 179)");  console.log("Wheat buttons:", wheat.length);</script>
    ResultLoading…

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

      Exercise 3 · PracticeRename a part without breaking pages

      Ravi renamed the quantity's shared part from button to step, and this page broke. It prints Wheat buttons: 0. Fix the tea-quantity.js tab so old pages keep working. What does the page print then?

      <style>  tea-quantity::part(button) { background: wheat; }</style><tea-quantity></tea-quantity> <script src="tea-quantity.js"></script><script>  const buttons = [...document.querySelector("tea-quantity").shadowRoot.querySelectorAll("button")];  const wheat = buttons.filter((button) => getComputedStyle(button).backgroundColor === "rgb(245, 222, 179)");  console.log("Wheat buttons:", wheat.length);</script>
      ResultLoading…

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

        Exercise 4 · PracticeForward the quantity from an order form

        A tea-order-form holds a quantity, and the page styles tea-order-form::part(qty-button). It prints Wheat buttons: 0. Make the form forward the buttons. What does your fixed page print?

        <style>  tea-order-form::part(qty-button) { background: wheat; }</style><tea-order-form></tea-order-form> <script src="tea-quantity.js"></script><script>  class TeaOrderForm extends HTMLElement {    constructor() {      super();      this.attachShadow({ mode: "open" }).innerHTML = `        <label>Cups <tea-quantity></tea-quantity></label>`;    }  }  customElements.define("tea-order-form", TeaOrderForm);   const quantity = document.querySelector("tea-order-form").shadowRoot.querySelector("tea-quantity");  const buttons = [...quantity.shadowRoot.querySelectorAll("button")];  const wheat = buttons.filter((button) => getComputedStyle(button).backgroundColor === "rgb(245, 222, 179)");  console.log("Wheat buttons:", wheat.length);</script>
        ResultLoading…

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

          Exercise 5 · ChallengeThe middle level forgot

          The page styles tea-panel::part(quantity-button), and the panel forwards it, but the page prints Minus button: plain. Fix it. What does your fixed page print?

          <style>  tea-panel::part(quantity-button) { background: sienna; }</style><tea-panel></tea-panel> <script src="tea-quantity.js"></script><script>  class TeaCard extends HTMLElement {    constructor() {      super();      this.attachShadow({ mode: "open" }).innerHTML = `        <tea-quantity></tea-quantity>`;    }  }  class TeaPanel extends HTMLElement {    constructor() {      super();      this.attachShadow({ mode: "open" }).innerHTML = `        <tea-card exportparts="quantity-button"></tea-card>`;    }  }  customElements.define("tea-card", TeaCard);  customElements.define("tea-panel", TeaPanel);   const card = document.querySelector("tea-panel").shadowRoot.querySelector("tea-card");  const less = card.shadowRoot.querySelector("tea-quantity").shadowRoot.querySelector("button");  const sienna = getComputedStyle(less).backgroundColor === "rgb(160, 82, 45)";  console.log("Minus button:", sienna ? "sienna" : "plain");</script>
          ResultLoading…

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

            Exercise 6 · ChallengeOne bad selector in a list

            Ravi wants a sienna Add button with a white icon. The page prints Add button: rgb(239, 239, 239), the browser's gray. Fix the rule. What does the first line print then?

            <style>  tea-card::part(add),  tea-card::part(add) svg { color: white; background: sienna; }</style><tea-card></tea-card> <script>  class TeaCard extends HTMLElement {    constructor() {      super();      this.attachShadow({ mode: "open" }).innerHTML = `        <button part="add"><svg width="10" height="10"><circle cx="5" cy="5" r="5" fill="currentColor"></circle></svg> Add 1</button>`;    }  }  customElements.define("tea-card", TeaCard);   const add = document.querySelector("tea-card").shadowRoot.querySelector("button");  console.log("Add button:", getComputedStyle(add).backgroundColor);  console.log("Icon:", getComputedStyle(add.querySelector("svg")).color);</script>
            ResultLoading…

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

              Check your understanding

              For each question, ask: which tree holds the part, and did every level on the way forward it?

              The parts quiz · 7 questionsScore: first tries count
              1. Question 1 of 7The quantity's buttons have part="button less" and part="button more". Which elements does tea-quantity::part(button) style?

                Choose an answer to see the explanation.

              2. Question 2 of 7What does this page print, with #add in the card and ::part(add) on the page?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <style>
                  tea-card::part(add) { background: sienna; }
                </style>
                <tea-card>Green tea</tea-card>
                
                <script>
                  class TeaCard extends HTMLElement {
                    constructor() {
                      super();
                      this.attachShadow({ mode: "open" }).innerHTML = `
                        <style>#add { background: white; }</style>
                        <h3><slot></slot></h3>
                        <button id="add" part="add">Add 1</button>`;
                    }
                  }
                  customElements.define("tea-card", TeaCard);
                
                  const add = document.querySelector("tea-card").shadowRoot.querySelector("button");
                  console.log("Add button:", getComputedStyle(add).backgroundColor);
                </script>

                Choose an answer to see the explanation.

              3. Question 3 of 7What does Chrome do with the rule tea-quantity::part(button):first-child { background: wheat; }?

                Choose an answer to see the explanation.

              4. Question 4 of 7The card holds <tea-quantity exportparts="button: quantity-button"> in its shadow root. Which page rule styles the quantity's buttons?

                Choose an answer to see the explanation.

              5. Question 5 of 7The panel holds a card with exportparts="quantity-button", but the card's own quantity has no exportparts. What does tea-panel::part(quantity-button) style?

                Choose an answer to see the explanation.

              6. Question 6 of 7Which is the best part name for the tea card's <h3> heading?

                Choose an answer to see the explanation.

              7. Question 7 of 7A page wants a soft shadow under the Add button. Should the kit offer a part or a custom property?

                Choose an answer to see the explanation.

              Key takeaways

              • Give an inner element a part name with part="add". Names work like classes: an element can have several, and many elements can share one.
              • The page styles a part with tea-card::part(add) and any CSS property. Its normal rules beat the component's. The component's !important beats the page.
              • :hover, :focus-visible, and ::before may follow ::part(). Structural pseudo-classes and combinators drop the whole rule.
              • A part is seen one level up. exportparts="button: quantity-button" forwards it under a new name, and every level must forward it.
              • ::part() never selects inside the part. Inherited properties still reach the part's children.
              • Name parts by their job, keep them few, and document each with @csspart and in cssParts. Use custom properties for theme values, and parts for open-ended styling.

              Remember the one-liner.
              The component fits the handles. The page can grip only those, one level at a time.

              Sources

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

              Coming next: Custom states and :state(). Parts let a page style the elements you name. Custom states let it style the states you name, like busy or sold out.

              CompleteFrontend Clear concepts. Working examples.