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.
- 01Name parts and style themGive inner elements
partnames, and style them from the page with::part(),:hover, and::before. - 02Pass parts up through nested componentsForward a nested component's parts with
exportparts, rename them, and find the level that forgot. - 03Design 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:
<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>- In the
tea-card.jstab, 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 nameadd. - Back on the page, lines 2 to 6 style the card's
addpart. 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.
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
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():
<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>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.
- In the
tea-quantity.jstab, lines 5 to 7 are the quantity's three elements. Line 5 is the - button, with two names:buttonandless. Line 7 is the + button:buttonandmore. Line 6 is the number, callednumber. - 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.
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().
<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>- 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
lessis one of its names. It printstrue. - Line 8 adds a third name,
minimum. Line 9 reads the attribute again. It printsbutton 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:
<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>It prints Add button: rgb(160, 82, 45). Both rules are normal, so the outer context wins: the page. The button is sienna.
- Line 2 is the page's rule. It makes the
addpart 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:
<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>- 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-quantityselector 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:
<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>It prints Rules kept: 1. Move the pointer over - or + in the result. The button under it turns wheat.
- 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 follows ::part(button) | Does Chrome keep the rule? | Why |
|---|---|---|
:hover, :focus, :focus-visible, :active | Yes. | They ask what the reader is doing to the part right now. |
:disabled, :enabled, :checked | Yes. | 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, ::placeholder | Yes. | They style a piece of the part itself. |
:first-child, :last-child, :nth-child(2), :only-child | No. 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) span | No. 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:
<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>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.
- Lines 2 to 4 are three page rules, for three names:
button,quantity-button, andquantity-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:
buttonforwards the part under the same name. It's short forbutton: button.button: quantity-buttonforwards the inner partbuttonunder the outer namequantity-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.
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.
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:
<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>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.
- Line 2 styles the panel's
quantity-buttonpart. - 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-childor: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>:
<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>- 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.
::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.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, noth3. If the card changes its heading to<h2>,nameis still true. - Name the job, not the look. Use
add, notsienna-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 islessormore. - Prefix a forwarded name.
quantity-buttonsays 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:
| Part | What it styles |
|---|---|
number-input | The outer wrapper around the whole control. |
input | The native <input> inside it. |
stepper | Both stepper buttons, so one rule styles them together. |
stepper-decrement | The - button on its own. |
stepper-increment | The + button on its own. |
base | The 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.
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:
/**
* 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:
"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
namepart, with itsnameand itsdescription. - 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".
: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
bodysets 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:
- 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
Put each request where it fits best in the tea kit's styling API.
Giving the tea kit a set of parts
Now the kit. Three files get parts:
tea-quantitynames its buttonsbutton,less, andmore, and its numbernumber.tea-cardnames the tea's namename, the price lineprice, and the Add buttonadd. It forwards the quantity'sbuttonasquantity-button.tea-panelnames its labellabel, 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:
<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>- In the
tea-kit/tea-card.jstab, lines 22 and 23 name the headingnameand the price lineprice. Line 27 forwards the quantity's buttons. Line 28 names the Add buttonadd. - In the
tea-kit/tea-panel.jstab, 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
addpart 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 withexportparts. - "
exportparts="button: quantity-button"forwards both names." No. Only the new one. Writebutton, button: quantity-buttonto keep both. - "A rule like
::part(button):first-childjust waits to match." No. Chrome drops the whole rule, as it does for::part(button) span. - "You can't put
::beforeor::afteron a part." No.tea-quantity::part(number)::beforeadds 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!importantwins. - "Part names ignore case, like HTML tags." No.
::part(Button)doesn't matchpart="button".
Practice exercises
Answer first, then use the hints. The pages run live, so you can check yourself.
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>The + button. Only it has both names, button and more. The page prints button more: wheat and plain for the rest.
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>Wheat buttons: 0. A renamed part is forwarded only under its new name, so tea-card::part(button) matches nothing.
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><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>In the tea-quantity.js tab, keep the old name next to the new one: part="step button less" and part="step button more". Both buttons match ::part(button) again, so the page prints Wheat buttons: 2. Document button as deprecated until the next major version.
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><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 exportparts="button: qty-button"></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>The form forwards the quantity's button part as its own qty-button. Line 2 matches both buttons, and the page prints Wheat buttons: 2.
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><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>The card now makes a quantity-button part, and the panel passes it on. The page prints Minus button: sienna.
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><style> tea-card::part(add) { 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>One invalid selector drops the whole rule, good selectors and all. With only tea-card::part(add), it prints Add button: rgb(160, 82, 45) and Icon: rgb(255, 255, 255): the icon inherits white.
Check your understanding
For each question, ask: which tree holds the part, and did every level on the way forward it?
Question 1 of 7The quantity's buttons have
part="button less"andpart="button more". Which elements doestea-quantity::part(button)style?Choose an answer to see the explanation.
Question 2 of 7What does this page print, with
#addin the card and::part(add)on the page?Read the code, then predict<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.
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.
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.
Question 5 of 7The panel holds a card with
exportparts="quantity-button", but the card's own quantity has noexportparts. What doestea-panel::part(quantity-button)style?Choose an answer to see the explanation.
Question 6 of 7Which is the best part name for the tea card's
<h3>heading?Choose an answer to see the explanation.
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!importantbeats the page. :hover,:focus-visible, and::beforemay 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
@csspartand incssParts. 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:
- ::part(), MDN.
- part, MDN.
- Element: part property, MDN.
- CSS Shadow Module Level 1: Exposing a shadow element, CSSWG Editor's Draft.
- CSS Cascading and Inheritance Level 5: Cascade context, CSSWG Editor's Draft.
- Author-defined CSS names and the shadow DOM, Noam Rosenthal, Chrome for Developers.
- exportparts, MDN.
- When To Create CSS Parts, Cory LaViska.
- Styling web components: ::part() and exportparts, Chrome for Developers, Modern Web Guidance.
- Number Input: CSS parts, Web Awesome.
- Button: CSS parts, Web Awesome.
- Custom Elements Manifest Analyzer: Supported JSDoc, Open Web Components.
- The Custom Elements Manifest schema, webcomponents.org.
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.