Custom properties as a styling API
Learn how CSS custom properties reach inside web components, and how to name them with a prefix, give them safe defaults, and document them.
- 01Expose a few well-named custom propertiesGive a component prefixed names like
--tea-card-bg, each read once into a private name with its default. - 02Predict what a component showsSay when a
var()fallback runs, and why a default set on:hoststops the page's value. - 03Register and document themRegister a typed property in the document, and list every public property with
@csspropand in the manifest.
How do you give a web component a styling API?
Leaf and Kettle is getting an autumn menu. Meena builds the menu page with the tea kit's cards. She wants every card on a warm wheat background. So she writes tea-card .card { background: wheat; }. Nothing changes.
She knows why. Page selectors stop at a shadow root, as lesson 6.3 showed, and the card's box lives inside one. So she asks Ravi, who builds the kit: how can a page change a card's colors without reaching inside?
A web component gives the page a styling API by reading CSS custom properties, like var(--tea-card-bg, white), inside its shadow root. Custom properties are inherited, so a value the page sets on the tag, or on anything around it, reaches inside. Give each one a prefixed name, a default, and a line in the docs.
A custom property is a CSS property whose name starts with two dashes, like --tea-card-bg. You pick the name, and CSS gives it no meaning of its own. var() reads its value in another rule. Lesson 2.3 set a library's custom properties from the page. Now you're on the other side. You decide which ones your component reads. Here is a small card that reads one:
<style> tea-card { --tea-card-bg: wheat; }</style><tea-card>Green tea</tea-card> <script src="tea-card.js"></script><script> const box = document.querySelector("tea-card").shadowRoot.querySelector(".card"); console.log("Background:", getComputedStyle(box).backgroundColor);</script>- In the
tea-card.jstab, line 4 gives the card a shadow root. Line 6 is the card's one rule. Its background isvar(--tea-card-bg, white): the value of--tea-card-bg, or white if it has none. - Line 8 of the tab is the card's box, a
divwith the classcard. The<slot>inside it shows the card's text. - Back on the page, line 2 sets
--tea-card-bgto wheat on everytea-card. - Line 8 finds the box inside the card's shadow root. Line 9 prints its background with
getComputedStyle(), which gives the value the browser really uses. Styles and classes covers it.
It prints Background: rgb(245, 222, 179). That's wheat, written as amounts of red, green, and blue. The page never touched the box. It set a value, and the card chose to use it. Press Edit & run and change wheat to lavender on line 2. It prints Background: rgb(230, 230, 250). Now put Meena's first try on line 2 instead, and the card stays white.
Leaf and Kettle's kitchen has a row of taps on the wall. Each has a label: hot water, cold water, milk. The plumber chose which taps to fit and labelled them. The staff choose what to pour from each one. Nobody opens the wall to get a drink.
- In real life: The plumber who fits the taps
- In CSS: The component's author, Ravi
- In real life: A tap with a label on it
- In CSS: A custom property the card reads, like
--tea-card-bg - In real life: What the staff pour through it
- In CSS: The value the page sets, like wheat
- In real life: Plain water, when nobody changes it
- In CSS: The fallback, white
- In real life: The wall around the pipes
- In CSS: The shadow root
A styling API is a short list of custom properties a component promises to read. The component picks the names and the defaults. The page picks the values, and sets them on the component or on anything around it.
How do CSS custom properties cross the shadow DOM boundary?
By inheritance. You've seen the result a few times. Lesson 6.1 listed custom properties among the things that pass into a shadow tree. Lesson 11.1 showed color and font-family flowing in, and custom properties staying even through all: initial. Here is why it works.
An inherited property is one an element takes from its parent, unless a rule gives the element its own value. Every custom property is inherited. The CSS Variables spec says so in the table for --*.
But which parent? The card's box sits inside a shadow root, not inside the page's section. CSS Cascade Level 5 answers it: inheritance runs on the flat tree. That's the tree the browser draws, where each shadow tree sits inside its host, as lesson 8.2 showed. In the flat tree, the box's parent is the host, and the host's parent is on the page.
So the page can set the value in more than one place. Pick where it sets wheat:
<style> /* The page sets nothing. */</style><section class="autumn"> <tea-card>Oolong</tea-card></section><tea-card>Green tea</tea-card> <script src="tea-card.js"></script><script> for (const tea of document.querySelectorAll("tea-card")) { const box = tea.shadowRoot.querySelector(".card"); console.log(tea.textContent, getComputedStyle(box).backgroundColor); }</script>It prints Oolong rgb(255, 255, 255) and Green tea rgb(255, 255, 255). Nothing sets --tea-card-bg, so var() uses its fallback, white, in both cards.
- Line 2 is the only line that changes. With Nowhere, it holds a comment.
- Lines 4 to 6 put Oolong inside a
sectionwith the classautumn. Line 7 puts Green tea outside it. - Line 9 loads the card from the
tea-card.jstab, the same card as before. - Lines 11 to 14 print each card's text and background.
With On body and On tea-card, both cards are wheat. With On a section, only Oolong is. With Nowhere, both use the fallback, white.
body, on the section, or on the card itself. Each element inherits it from the one above. In the flat tree, the shadow root's box is one more step down, so the value keeps going.Why it matters: a page can theme one card, one section, or the whole page, with one name. Your component never needs to know which. The value also keeps going through every shadow root on the way down. A card inside another component's shadow root gets it too. The practical at the end shows one.
How should you name a web component's custom properties?
Custom properties cross into your component on purpose. So the page's own custom properties cross in too. Pages use them for their own colors and spacing. If your card reads a name the page already uses, the page's value gets in.
Leaf and Kettle's site sets --color: crimson on :root, for its headings. Ravi's first card reads --color too. Switch between two names for the card's rule:
<style> :root { --color: crimson; } h1 { color: var(--color); }</style><h1>Leaf and Kettle</h1><tea-card>Green tea</tea-card> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }).innerHTML = ` <style>.card { color: var(--color, seagreen); }</style> <div class="card"><slot></slot></div>`; } } customElements.define("tea-card", TeaCard); const box = document.querySelector("tea-card").shadowRoot.querySelector(".card"); console.log("Card text:", getComputedStyle(box).color);</script>It prints Card text: rgb(220, 20, 60). The page made --color crimson for its own heading. It inherits into the card, which reads the same name, so Green tea turns crimson.
- Line 2 is the page's own custom property. Line 3 uses it for the page's heading.
- Lines 9 to 17 are the card, written in the page this time. Line 13 is its one rule. With the first choice, it reads
var(--color, seagreen). - Lines 19 and 20 print the color of the card's text.
With --color, it prints Card text: rgb(220, 20, 60), crimson. The page never meant to style the card. With --tea-card-accent, it prints Card text: rgb(46, 139, 87), the card's seagreen.
Shadow DOM keeps selectors apart, but not names. One custom property name means the same thing in every tree on the page. So give each name a prefix: a start that says whose it is.
Leaf and Kettle calls out orders by name. One morning, two customers are called Sam. The barista calls "Sam!" and both stand up. So she adds the family name: "Sam Rao, your oolong." Only one person stands.
- In real life: Calling out "Sam!"
- In CSS: Reading
--color - In real life: Both Sams standing up
- In CSS: The page's value reaching the card
- In real life: "Sam Rao, your oolong"
- In CSS: A prefixed name,
--tea-card-accent - In real life: Only one person standing
- In CSS: Only the value meant for the card
A naming pattern for the kit
- Start with the kit:
--tea-. Every name the kit reads starts the same way, so a page can tell at once whose it is. - For one component's own values, add the component:
--tea-card-bg,--tea-card-accent. - For values every kit component shares, leave the component out:
--tea-radius, like lesson 11.7's--tea-font-display. - End with the job, not the value:
--tea-card-accent, not--tea-card-green. A page may set it to brown.
Names are case-sensitive, MDN notes. --Tea-Card-Bg is a different property from --tea-card-bg. Use lowercase with hyphens, like every CSS property. Exercise 2 shows what a capital does.
How Web Awesome names them
Web Awesome, the library from lesson 2.1, uses two kinds of names. Its docs on customizing say every theme token starts with --wa-, "to prevent collisions with other libraries". Its components also read short names, like --size and --background-color. Those are set on the component itself, as in wa-avatar { --size: 6rem; }. The section on body values below shows how that works.
The CSS spec for registered properties gives the same advice for names a component only uses inside: give them "a likely-unique name". Now sort a few names:
--tea-card-bg--tea-radius--_bg--color--tea-card-green--Tea-Card-Bg
Put each custom property name where it belongs in the tea card's styling API.
When does a var() fallback value apply?
Every name in your API needs a default: what the card shows when the page sets nothing. The second value in var() is the fallback. In var(--tea-card-bg, white), it's white.
But "the page sets nothing" isn't the only case. Try five values for --tea-card-bg, all set on body:
<style> /* The page sets nothing. */</style><tea-card>Green tea</tea-card> <script src="tea-card.js"></script><script> const box = document.querySelector("tea-card").shadowRoot.querySelector(".card"); console.log("Background:", getComputedStyle(box).backgroundColor);</script>It prints Background: rgb(255, 255, 255). Nothing sets --tea-card-bg. It has no value at all, so var() uses white.
- Line 2 is the only line that changes.
- Line 4 is the card. Line 9 prints its background.
- The card stays the same. In the
tea-card.jstab, line 6 readsvar(--tea-card-bg, white).
The first three print white: Not set, initial, and var(--shop-paper). hotpink prints Background: rgb(255, 105, 180). And 16px prints Background: rgba(0, 0, 0, 0), a see-through box. Not white.
MDN's page on var() gives the rule. The fallback runs only when the property has no usable value. The spec calls that the guaranteed-invalid value, which means "no value". A custom property has it when:
- nothing sets it;
- it's set to
initial, which resets a custom property to no value; - its own value can't be worked out, like
var(--shop-paper)when nothing sets--shop-paper.
Pointing a name at another variable is common. It's how a page wires its own colors into a component: body { --tea-card-bg: var(--shop-paper); }. Once the page also sets --shop-paper: ivory, the card prints Background: rgb(255, 255, 240).
hotpink is a value. So is 16px. A fallback can't protect the card from a value it doesn't like.
var(--tea-card-bg, white) only asks one question: does the property have a usable value? If not, it uses white. If it does, it uses that value, even 16px, and never comes back to the fallback.Why see-through, and not white? A custom property can hold almost anything. So the browser can't check 16px when the page sets it. It checks only when background uses it. By then, MDN explains, the other values have been thrown away. So background acts as if it were unset. A background isn't inherited, so unset means its starting value: transparent.
Leaf and Kettle lets you bring your own cup. If you bring none, the staff pour your tea into a shop mug. If you bring a bright pink cup, they use it, even if it clashes. If you hand over a sieve, they pour anyway, and the tea runs straight through.
- In real life: The shop mug
- In CSS: The fallback, white
- In real life: Bringing no cup
- In CSS: Nothing sets
--tea-card-bg - In real life: The bright pink cup
- In CSS: hotpink, a real value, used as it is
- In real life: The sieve
- In CSS: 16px, a value
backgroundcan't hold - In real life: Tea running through it
- In CSS: A see-through box
Why it matters: a fallback is the default for a page that says nothing. It isn't a guard against bad values. The section on @property shows one that is.
Why doesn't a custom property on body reach my component?
A component can put a default in a second place: on itself, with :host. It looks tidy. Ravi writes :host { --tea-card-bg: white; } once, then var(--tea-card-bg) with no fallback. Meena sets lavender on body, and her cards stay white.
Switch between Ravi's two versions of the card:
<style> body { --tea-card-bg: lavender; } .special { --tea-card-bg: wheat; }</style><tea-card>Green tea</tea-card><tea-card class="special">Oolong</tea-card> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }).innerHTML = ` <style> :host { --tea-card-bg: white; } .card { background: var(--tea-card-bg); } </style> <div class="card"><slot></slot></div>`; } } customElements.define("tea-card", TeaCard); for (const tea of document.querySelectorAll("tea-card")) { const box = tea.shadowRoot.querySelector(".card"); console.log(tea.textContent, getComputedStyle(box).backgroundColor); }</script>It prints Green tea rgb(255, 255, 255) and Oolong rgb(245, 222, 179). Line 14 gives the host its own --tea-card-bg, so it doesn't inherit the body's. Only .special, a rule on the tag itself, gets through.
- Line 2 sets lavender on
body. Line 3 sets wheat on anything with the classspecial. - Line 5 is Green tea. Line 6 is Oolong, with the class
special. - With A default on :host, line 14 sets the public name on the host, and line 15 reads it.
- Lines 22 to 25 print each card's text and background.
With the default on :host, it prints Green tea rgb(255, 255, 255) and Oolong rgb(245, 222, 179). Green tea is white, and Oolong is wheat. The body's lavender never arrived.
Two rules you already know explain it:
- Inheritance only fills a gap. An element takes its parent's value only when no rule gives it one. The
:hostrule gives the host its own--tea-card-bg, so there's no gap. Lesson 2.3 saw a Web Awesome rating keep its star color this way. - The
.specialrule matches the host itself. When a page rule and a:hostrule set the same property on the host, the page wins, as lesson 11.4 showed.
So only a rule that matches the tag itself can change the value. It's like a cupboard that already has a label stuck on it: a note on the staff board doesn't change it, but a new label on that cupboard does. Chrome's guide to styling web components gives the same advice. It calls this "seeding" the public property on :host, and says not to do it.
:host gives the host its own --tea-card-bg, so it never takes the body's. On the right, the card never sets the public name. The host inherits lavender, and --_bg copies it.Public and private custom properties
The second choice fixes it, and still keeps the default in one place. The card never sets the public name. It copies it into a name of its own:
:host {
--_bg: var(--tea-card-bg, white);
}
.card { background: var(--_bg); }- Line 2 reads the public name,
--tea-card-bg, with white as the fallback. It stores the result in--_bg. - Line 4 uses
--_bg. Any rule in the card can, without repeating the fallback.
Now the host has no --tea-card-bg of its own, so it inherits lavender from body. Line 2 turns that into --_bg: lavender. The second choice prints Green tea rgb(230, 230, 250) and Oolong rgb(245, 222, 179). Oolong's own wheat still wins on its tag.
So a styling API has two kinds of names:
- A public custom property, like
--tea-card-bg, is for the page. The component reads it and never sets it. It goes in the docs. - A private custom property, like
--_bg, is for the component. The underscore at the start is a common sign for "inside use only". The component sets it on:host, and the docs never list it.
The underscore is a sign, not a lock. A page rule like tea-card { --_bg: hotpink; } still matches the host, and still beats :host. That's why you leave private names out of the docs. A page that uses one may break on your next release.
When a library sets them on :host on purpose
Some libraries choose the first version on purpose. Web Awesome's rating, from lesson 2.3, sets its --symbol-color-active on :host, so only a rule on the tag changes it. Web Awesome's docs say to set component properties on the component, as in wa-avatar { --size: 6rem; }. The upside: a short name like --size that a page sets on body for its own reasons can't get in. Nolan Lawson describes the Ionic library doing the same. Choose one style for a kit, and say it in the docs. The tea kit uses prefixed names and private copies, so a value set anywhere above a card reaches it.
Does @property work in shadow DOM?
Not inside a shadow root. First, what it does. A plain custom property holds any text. @property registers a custom property: it tells the browser three things about it.
syntax: what kind of value it takes, like"<color>".inherits: whether elements take it from their parent.initial-value: its value when nothing sets it.
Meena's page has a typo: siena instead of sienna. This page registers --tea-card-accent as a color first:
<style> @property --tea-card-accent { syntax: "<color>"; inherits: true; initial-value: seagreen; } body { --tea-card-accent: siena; }</style><tea-card>Green tea</tea-card> <script src="tea-card.js"></script><script> const box = document.querySelector("tea-card").shadowRoot.querySelector(".card"); console.log("Accent:", getComputedStyle(box).getPropertyValue("--tea-card-accent")); console.log("Name:", getComputedStyle(box).color);</script>- Lines 2 to 6 register
--tea-card-accent: a color, inherited, and seagreen when nothing sets it. - Line 7 sets it to siena on
body. siena isn't a color name. - In the
tea-card.jstab, line 6 colors the card's text and border withvar(--tea-card-accent, seagreen). - Line 14 prints the property's value inside the card. Line 15 prints the text color.
It prints Accent: rgb(46, 139, 87) and Name: rgb(46, 139, 87). The browser checked siena against <color> and dropped it, so the card got the initial value, seagreen. Delete lines 2 to 6 and run it again. It prints Accent: siena and Name: rgb(0, 0, 0). Without the type, the typo gets all the way to color, which can't use it.
A registered color can also fade from one value to the next with a transition. An unregistered custom property just jumps, because the browser doesn't know what kind of value it holds. MDN's @property page animates one.
Where the @property rule must go
Ravi's first thought is to keep the rule with the card, inside its shadow root. Try both places:
<style> @property --tea-card-accent { syntax: "<color>"; inherits: true; initial-value: seagreen; } body { --tea-card-accent: siena; }</style><tea-card>Green tea</tea-card> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }).innerHTML = ` <style> /* No @property here. */ .card { padding: 8px; border: 2px solid; color: var(--tea-card-accent, seagreen); } </style> <div class="card"><slot></slot></div>`; } } customElements.define("tea-card", TeaCard); const box = document.querySelector("tea-card").shadowRoot.querySelector(".card"); console.log("Accent:", getComputedStyle(box).getPropertyValue("--tea-card-accent"));</script>It prints Accent: rgb(46, 139, 87). The page's rule registers --tea-card-accent as a color. siena isn't one, so the browser drops it, and the card gets the initial value, seagreen.
- With In the page, line 2 holds the rule. With In the shadow root, line 13, inside the card's
<style>, holds it. - Line 3 sets the typo, siena, on
body. - Line 22 prints the property's value inside the card.
In the page, it prints Accent: rgb(46, 139, 87). In the shadow root, it prints Accent: siena, and the name turns black. The rule did nothing.
The spec says it should work. The CSS Properties and Values spec keeps one list of registrations for the whole document, wherever the rule sits. But Chrome's article on CSS names reports that every browser ignores @property inside a shadow root. Adobe's shadow DOM tracker shows Chrome, Edge, Firefox, and Safari all failing the tests for it. Lesson 11.7 found the same for @font-face in Chrome and Firefox. Put rules like these in the document.
@property inside a shadow root, so only the page's rule registers --tea-card-accent as a color. Then a typo like siena is thrown out, and the card keeps seagreen.Leaf and Kettle has one sign on its front door: "Teas come small, medium, or large." Every customer reads it on the way in, whichever room they sit in. Once, the kitchen taped up its own sign inside. No customer ever saw it.
- In real life: The sign on the front door
- In CSS:
@propertyin the document - In real life: "Small, medium, or large"
- In CSS:
syntax: "<color>" - In real life: Every room following it
- In CSS: One registration for the whole page, shadow roots included
- In real life: The kitchen's own sign, taped inside
- In CSS:
@propertyinside a shadow root
Registering from the component's file
A component can't put the rule in its shadow root. But its file can still register the name. CSS.registerProperty() does the same as @property, from JavaScript, and always for the whole document:
<style> body { --tea-card-accent: siena; }</style><tea-card>Green tea</tea-card> <script src="tea-card.js"></script><script> const box = document.querySelector("tea-card").shadowRoot.querySelector(".card"); console.log("Accent:", getComputedStyle(box).getPropertyValue("--tea-card-accent"));</script>- In the
tea-card.jstab, lines 2 to 7 register--tea-card-accentwith the same three facts. In JavaScript,initial-valueis writteninitialValue. - Lines 1 and 8 wrap it in
tryandcatch. A second call for the same name throws anInvalidModificationError: "The name provided has already been registered." That happens if another script registers it first. - On the page, line 2 sets siena again. Line 9 prints the value inside the card.
It prints Accent: rgb(46, 139, 87). The file runs once, so it registers once, however many cards the page has. If the page also has an @property rule for the name, the JavaScript registration wins, MDN notes.
Two things registration changes
- With an
initial-value, the property always has a value. So the fallback invar()never runs. Exercise 4 shows it. - With
inherits: false, a value set onbodyor a section stays there. The card only sees a value set on its own tag. For a styling API, register withinherits: true. Exercise 5 fixes this mistake.
Here are four ways to give the card a default. Each row ran in Chrome with three cards. One sits inside a section that sets wheat. One has wheat on its own tag. One has 16px on its own tag. Read each row across:
| Where the default lives | Wheat on an element around the card | Wheat on the tea-card tag | 16px on the tea-card tag |
|---|---|---|---|
A fallback in var(--tea-card-bg, white) | Wheat arrives. | Wheat arrives. | No fallback. The box is see-through. |
The public name set on :host | It never arrives. The card stays white. | Wheat arrives. | No fallback. The box is see-through. |
A private name, --_bg: var(--tea-card-bg, white) | Wheat arrives. | Wheat arrives. | No fallback. The box is see-through. |
initial-value: white in the page's @property | Wheat arrives. | Wheat arrives. | The bad value is dropped. The card is white. |
Only a fallback in var(), a private name, and a registered property let a value through from anywhere. Only the registered property drops a bad value. The kit uses private names, and leaves registration to the page.
Colors for light and dark mode use light-dark(), which picks one of two colors from the inherited color-scheme, as lesson 2.3 showed. The themes lesson in Design systems builds whole light and dark themes on tokens like these.
How do you document a component's CSS custom properties?
A name nobody can find isn't an API. Lesson 5.4 listed what every component should document, custom properties included, and wrote JSDoc tags for the analyzer. Lesson 11.7 documented the kit's first custom property, --tea-font-display. For each public name, write down:
- its name;
- what it styles;
- what kind of value it takes, like a color or a length;
- its default.
Leave the private names out.
The @cssprop tag
Here is the kit card's JSDoc after this lesson, shortened to its custom properties:
/**
* 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
* @cssprop [--tea-font-display=Georgia, serif] - The font stack for the tea's name. The page declares the font with @font-face.
* @cssprop [--tea-card-bg=white] - The card's background color.
* @cssprop [--tea-card-accent=seagreen] - The color of the card's border and the tea's name.
* @cssprop [--tea-radius=8px] - How round the card's corners are. Other kit components can share it.
*/- Line 4 names the tag.
- Lines 5 to 8 each describe one custom property with
@cssprop. The analyzer also accepts@cssproperty. - Each name sits in square brackets, with its default after
=, as in[--tea-card-bg=white]. The words after the dash say what it styles, and so what kind of value it takes.
The default needs the brackets. The analyzer's own test file shows it: [--background-color=red] gives a default of red. Words like "Default: white." stay in the description. Lesson 11.7 wrote --tea-font-display's default that way, so line 5 moves it into brackets too.
The manifest entry
The analyzer turns those four lines into the cssProperties list of the card's entry in custom-elements.json. The kit writes its manifest by hand, to match:
"cssProperties": [
{
"name": "--tea-font-display",
"description": "The font stack for the tea's name. The page declares the font with @font-face.",
"default": "Georgia, serif"
},
{
"name": "--tea-card-bg",
"description": "The card's background color.",
"default": "white"
},
{
"name": "--tea-card-accent",
"description": "The color of the card's border and the tea's name.",
"default": "seagreen"
},
{
"name": "--tea-radius",
"description": "How round the card's corners are. Other kit components can share it.",
"default": "8px"
}
]- Line 1 starts the list. Lines 2 to 6 are
--tea-font-display's entry, with its default on line 5. - Lines 7 to 11 are
--tea-card-bg's: itsname, itsdescription, and itsdefault, white. - Lines 12 to 21 are the accent and the radius, in the same shape.
Docs pages like the Web Awesome tables from lesson 2.1 are made from files like this one.
A table for the docs
People reading your docs want a table. Here is the card's, made from the same four entries. Read each row across:
| Custom property | What it styles | Default |
|---|---|---|
--tea-font-display | The font stack for the tea's name. The page declares the font with @font-face. | Georgia, serif |
--tea-card-bg | The card's background color. | white |
--tea-card-accent | The color of the card's border and the tea's name. | seagreen |
--tea-radius | How round the card's corners are. Other kit components can share it. | 8px |
Why it matters: every row is a promise. Renaming --tea-card-bg breaks every page that sets it, so it needs a new major version, as lesson 5.4 explained. Keep the list short. A few well-named properties are easier to keep than twenty.
Giving the tea card a styling API
Now the kit. Its tea-card gets three new public names: --tea-card-bg, --tea-card-accent, and the kit-wide --tea-radius. Meena's autumn menu uses them:
<style> .autumn { --tea-card-bg: wheat; --tea-card-accent: sienna; } .square { --tea-radius: 0; }</style><section class="autumn"> <tea-card name="Oolong" price="5"></tea-card> <tea-panel><span slot="heading">Black tea</span></tea-panel></section><tea-card class="square" name="Green tea" price="4"></tea-card> <script type="module"> import "./tea-kit/index.js"; const inPanel = document.querySelector("tea-panel").shadowRoot.querySelector("tea-card"); for (const card of [...document.querySelectorAll("tea-card"), inPanel]) { const box = getComputedStyle(card.shadowRoot.querySelector(".card")); console.log(box.backgroundColor, box.borderTopColor, box.borderTopLeftRadius); }</script>- In the
tea-kit/tea-card.jstab, lines 5 to 9 are the new:hostrule. It reads each public name into a private one, with its default: white, seagreen, and 8px. - Line 10 of the tab draws the box with
--_accent,--_radius, and--_bg. Line 11 colors the tea's name with--_accent. - On the page, line 2 sets the autumn colors on the section. Line 3 makes the corners square on anything with the class
square. - Lines 6 and 7 put Oolong and a
tea-panelin the section. The panel keeps a kit card in its own shadow root, as in lesson 8.3. - Line 9 is Green tea, outside the section, with square corners.
- Line 13 finds the card inside the panel. Lines 14 to 17 print each card's background, border color, and corner radius.
It prints three lines. Oolong: rgb(245, 222, 179) rgb(160, 82, 45) 8px. Green tea: rgb(255, 255, 255) rgb(46, 139, 87) 0px. The panel's card: rgb(245, 222, 179) rgb(160, 82, 45) 8px. That card crossed two shadow roots, the panel's and its own, and still got the autumn colors.
Press Edit & run and change .autumn on line 2 to body. Green tea turns wheat too, with a sienna border.
The kit's JSDoc and manifest now list all four names. A page that sets nothing sees the same cards as before, on white. Lesson 12.6, in Styling web components, organizes names like these into a token system for the whole kit.
Common mix-ups
- "Shadow DOM blocks every page style, custom properties too." No. Custom properties are inherited, and inheritance runs on the flat tree, into every shadow root.
- "A page has to set the property on the component's tag." No. Any element around the card works, unless the component sets the public name on
:host. - "The fallback in
var()catches bad values." No. It runs only when the property has no usable value. hotpink is used as it is, and 16px makes the box see-through. - "
:host { --tea-card-bg: white; }works like a fallback." No. It gives the host its own value, so a value onbodyor a section never arrives. - "An underscore makes a custom property private." No. It's only a sign. A page rule on the tag can still set it, so keep it out of the docs.
- "
@propertyin a component's styles registers the property." No. Every browser ignores it inside a shadow root. Register in the document, or withCSS.registerProperty(). - "Short names like
--colorare friendlier." No. The page may already use them, and its value leaks into your component.
Practice exercises
Answer first, then use the hints. The pages run live, so you can check yourself.
The page sets hotpink on body and initial on the card. What does the page print?
<style> body { --tea-card-bg: hotpink; } tea-card { --tea-card-bg: initial; }</style><tea-card>Green tea</tea-card> <script src="tea-card.js"></script><script> const box = document.querySelector("tea-card").shadowRoot.querySelector(".card"); console.log("Background:", getComputedStyle(box).backgroundColor);</script>Background: rgb(255, 255, 255). The tag's own initial wins over the body's hotpink, and it means no value. So var(--tea-card-bg, white) uses white.
The page sets --Tea-Card-Bg to wheat on the card. What does the page print?
<style> tea-card { --Tea-Card-Bg: wheat; }</style><tea-card>Green tea</tea-card> <script src="tea-card.js"></script><script> const box = document.querySelector("tea-card").shadowRoot.querySelector(".card"); console.log("Background:", getComputedStyle(box).backgroundColor);</script>Background: rgb(255, 255, 255). The page set a different property. Nothing sets --tea-card-bg, so the card uses its fallback, white.
The section sets sienna, but Oolong stays seagreen, and the page prints Name: rgb(46, 139, 87). Fix the card's two rules. What does your fixed page print?
<style> .autumn { --tea-card-accent: sienna; }</style><section class="autumn"> <tea-card>Oolong</tea-card></section> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }).innerHTML = ` <style> :host { --tea-card-accent: seagreen; } .card { color: var(--tea-card-accent); } </style> <div class="card"><slot></slot></div>`; } } customElements.define("tea-card", TeaCard); const box = document.querySelector("tea-card").shadowRoot.querySelector(".card"); console.log("Name:", getComputedStyle(box).color);</script><style> .autumn { --tea-card-accent: sienna; }</style><section class="autumn"> <tea-card>Oolong</tea-card></section> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }).innerHTML = ` <style> :host { --_accent: var(--tea-card-accent, seagreen); } .card { color: var(--_accent); } </style> <div class="card"><slot></slot></div>`; } } customElements.define("tea-card", TeaCard); const box = document.querySelector("tea-card").shadowRoot.querySelector(".card"); console.log("Name:", getComputedStyle(box).color);</script>The card no longer sets the public name, so the host inherits sienna from the section. --_accent copies it, and the page prints Name: rgb(160, 82, 45).
The page registers --tea-card-bg and never sets it. The card reads var(--tea-card-bg, white). What does the page print?
<style> @property --tea-card-bg { syntax: "<color>"; inherits: true; initial-value: transparent; }</style><tea-card>Green tea</tea-card> <script src="tea-card.js"></script><script> const box = document.querySelector("tea-card").shadowRoot.querySelector(".card"); console.log("Background:", getComputedStyle(box).backgroundColor);</script>Background: rgba(0, 0, 0, 0). A registered property with an initial value always has one, here transparent. So the card's white fallback never runs.
The page registers --tea-card-accent and sets sienna on the section, but the page prints Name: rgb(46, 139, 87). Fix the registration. What does your fixed page print?
<style> @property --tea-card-accent { syntax: "<color>"; inherits: false; initial-value: seagreen; } .autumn { --tea-card-accent: sienna; }</style><section class="autumn"> <tea-card>Oolong</tea-card></section> <script src="tea-card.js"></script><script> const box = document.querySelector("tea-card").shadowRoot.querySelector(".card"); console.log("Name:", getComputedStyle(box).color);</script><style> @property --tea-card-accent { syntax: "<color>"; inherits: true; initial-value: seagreen; } .autumn { --tea-card-accent: sienna; }</style><section class="autumn"> <tea-card>Oolong</tea-card></section> <script src="tea-card.js"></script><script> const box = document.querySelector("tea-card").shadowRoot.querySelector(".card"); console.log("Name:", getComputedStyle(box).color);</script>With inherits: false, the value stayed on the section, and the card got the initial value. With inherits: true, the card inherits sienna, and the page prints Name: rgb(160, 82, 45).
The page sets --tea-radius: 0 on body, but the badge keeps its round corners and prints Badge corners: 8px. Give the badge the kit-wide name, through a private one. What does your page print?
<style> body { --tea-radius: 0; }</style><tea-badge>Organic</tea-badge> <script> class TeaBadge extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }).innerHTML = ` <style> :host { display: inline-block; padding: 0 6px; border-radius: 8px; background: dimgray; color: white; } </style> <slot></slot>`; } } customElements.define("tea-badge", TeaBadge); const badge = document.querySelector("tea-badge"); console.log("Badge corners:", getComputedStyle(badge).borderTopLeftRadius);</script><style> body { --tea-radius: 0; }</style><tea-badge>Organic</tea-badge> <script> class TeaBadge extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }).innerHTML = ` <style> :host { --_radius: var(--tea-radius, 8px); } :host { display: inline-block; padding: 0 6px; border-radius: var(--_radius); background: dimgray; color: white; } </style> <slot></slot>`; } } customElements.define("tea-badge", TeaBadge); const badge = document.querySelector("tea-badge"); console.log("Badge corners:", getComputedStyle(badge).borderTopLeftRadius);</script>The badge reads --tea-radius into --_radius, with 8px as the default. The page sets 0 on body, so the page prints Badge corners: 0px.
Check your understanding
For each question, ask: does the property have a usable value here, and where did it come from?
Question 1 of 7The page sets
body { --tea-card-bg: wheat; }. Why can a.cardinside the card's shadow root read it?Choose an answer to see the explanation.
Question 2 of 7What does this page print, with
16pxfor a background?Read the code, then predict<style> body { --tea-card-bg: 16px; } </style> <tea-card>Green tea</tea-card> <script src="tea-card.js"></script> <script> const box = document.querySelector("tea-card").shadowRoot.querySelector(".card"); console.log("Background:", getComputedStyle(box).backgroundColor); </script>Choose an answer to see the explanation.
Question 3 of 7What does this page print, with a default on
:host?Read the code, then predict<style> body { --tea-card-bg: wheat; } </style> <tea-card>Green tea</tea-card> <script> customElements.define("tea-card", class extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }).innerHTML = ` <style> :host { --tea-card-bg: white; } .card { background: var(--tea-card-bg); } </style> <div class="card"><slot></slot></div>`; } }); const box = document.querySelector("tea-card").shadowRoot.querySelector(".card"); console.log(getComputedStyle(box).backgroundColor); </script>Choose an answer to see the explanation.
Question 4 of 7Which is the best public name for the color of the card's border?
Choose an answer to see the explanation.
Question 5 of 7A component's own
<style>holds@property --tea-card-accent { ... }. What does the browser do with it?Choose an answer to see the explanation.
Question 6 of 7The page registers
--tea-card-accentwithinherits: false, then sets it on a section around the card. What color is the card's name?Choose an answer to see the explanation.
Question 7 of 7Which JSDoc line makes the Custom Elements Manifest Analyzer write
"default": "white"?Choose an answer to see the explanation.
Key takeaways
- Custom properties are inherited, and inheritance runs on the flat tree. A value set on the tag, or on anything around it, reaches inside.
- Give every public name a prefix: the kit, then the component, then the job, like
--tea-card-bg. var(--tea-card-bg, white)uses white only when--tea-card-bghas no usable value: not set,initial, or a missing variable. A wrong value isn't caught.- Never set a public name on
:host. Read it into a private one,--_bg: var(--tea-card-bg, white), and use that. @propertyadds a type, an initial value, and inheritance. Every browser ignores it in a shadow root, so register in the document.- Document each public name with
@cssprop [--name=default], in the manifest'scssProperties, and in a table.
Remember the one-liner.
The component names the taps and their defaults. The page decides what flows through them.
Sources
The facts on this page come from these standards, docs, and tools:
- Using CSS custom properties (variables), MDN.
- CSS Cascading and Inheritance Level 5: Inheritance, CSSWG Editor's Draft.
- CSS Shadow Module Level 1: The flat tree, CSSWG Editor's Draft.
- CSS Custom Properties for Cascading Variables Level 1, CSSWG Editor's Draft.
- Styling web components, Chrome for Developers, Modern Web Guidance.
- Customizing and theming: custom properties, Web Awesome.
- var(), MDN.
- @property, MDN.
- CSS Properties and Values API Level 1: Shadow DOM, CSS-TAG Houdini Editor's Draft.
- Author-defined CSS names and the shadow DOM: @property, Noam Rosenthal, Chrome for Developers.
- Shadow DOM and CSS: @property, Adobe.
- CSS: registerProperty() static method, MDN.
- Custom Elements Manifest Analyzer: Getting started, Open Web Components.
- The analyzer's JSDoc fixture, with a default in brackets, Open Web Components.
Coming next: Styling parts with ::part and exportparts. Custom properties let a page change the values you chose. Parts let it style a whole element you name.