completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

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.

By the end, you can
  • 01
    Expose a few well-named custom propertiesGive a component prefixed names like --tea-card-bg, each read once into a private name with its default.
  • 02
    Predict what a component showsSay when a var() fallback runs, and why a default set on :host stops the page's value.
  • 03
    Register and document themRegister a typed property in the document, and list every public property with @cssprop and 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:

A card that reads --tea-card-bg, and a page that sets itPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • In the tea-card.js tab, line 4 gives the card a shadow root. Line 6 is the card's one rule. Its background is var(--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 div with the class card. The <slot> inside it shows the card's text.
  • Back on the page, line 2 sets --tea-card-bg to wheat on every tea-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.

Real-life analogyLabelled taps on the shop wall

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
The main idea

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:

Playground: where the page sets the property
Two cards, and one rule that sets --tea-card-bgPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
Both cards use the fallback

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.

Only line 2 changes. Oolong sits inside the autumn section; Green tea doesn't. Watch both backgrounds.
  • Line 2 is the only line that changes. With Nowhere, it holds a comment.
  • Lines 4 to 6 put Oolong inside a section with the class autumn. Line 7 puts Green tea outside it.
  • Line 9 loads the card from the tea-card.js tab, 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.

A column of four cards, joined by arrows labelled inherits: body, section.autumn, tea-card, and, inside a window labelled shadow root, div.card. On the right, a card --tea-card-bg: wheat has an arrow into body, with the note or on the section, or on the card. Beside div.card: var(--tea-card-bg, white), and the note gives wheat.bodyinheritssection.autumninheritstea-cardshadow rootdiv.card--tea-card-bg: wheator on the section, or the cardvar(--tea-card-bg, white)gives wheat
Line 2 can set wheat on 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:

Playground: a short name or a prefixed one
A page that uses --color, and a card that reads a custom propertyPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
The page's variable leaks in

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.

Only line 13 changes: the name the card reads. The page's own --color on line 2 stays.
  • 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.

Real-life analogyTwo customers named Sam

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:

Sort the names
  • --tea-card-bg
  • --tea-radius
  • --_bg
  • --color
  • --tea-card-green
  • --Tea-Card-Bg
Try it yourself
0 of 6 correct

Put each custom property name where it belongs in the tea card's styling API.

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

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:

Playground: when the fallback runs
One card, and one value for --tea-card-bgPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
No value, so the fallback

It prints Background: rgb(255, 255, 255). Nothing sets --tea-card-bg. It has no value at all, so var() uses white.

Only line 2 changes. The card's line 6, in the tea-card.js tab, always reads var(--tea-card-bg, 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.js tab, line 6 reads var(--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.

Two halves. On the left, no usable value: three cards, not set, initial, and var(--shop-paper). An arrow goes down to a card that says white, with the note so the fallback runs. On the right, a value, used as it is. hotpink has an arrow to hotpink, noted used as it is. 16px has an arrow to see-through, noted background can't use it. At the bottom: so the fallback never runs.No usable valuenot setinitialvar(--shop-paper)whiteso the fallback runsA value, used as it ishotpinkhotpinkused as it is16pxsee-throughbackground can't use itso the fallback never runs
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.

Real-life analogyBring your own cup

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 background can'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:

Playground: where the card keeps its default
Lavender on body, wheat on one cardPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
The body's lavender never arrives

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.

Only lines 14 and 15 change. The page sets lavender on body and wheat on the special card.
  • Line 2 sets lavender on body. Line 3 sets wheat on anything with the class special.
  • 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 :host rule 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 .special rule matches the host itself. When a page rule and a :host rule 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.

Two columns, for the rows body, tea-card, and .card. Left column, a default on :host: body holds --tea-card-bg: lavender; under it, not inherited; tea-card holds --tea-card-bg: white; an arrow down to .card, background: white. Green tea: white. Right column, a private name: body holds --tea-card-bg: lavender; an arrow labelled inherited down to tea-card, which holds --_bg: lavender; an arrow down to .card, background: lavender. Green tea: lavender.A default on :hostA private namebodytea-card.card--tea-card-bg: lavendernot inherited--tea-card-bg: whitebackground: whiteGreen tea: white--tea-card-bg: lavenderinherited--_bg: lavenderbackground: lavenderGreen tea: lavender
On the left, :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:

A public name, read into a private oneCSS
: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:

A registered color, and a typoPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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.js tab, line 6 colors the card's text and border with var(--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:

Playground: where the @property rule goes
The same @property rule, in the page or in the shadow rootPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
Registered, so the typo is thrown out

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.

Only lines 2 and 13 change: the same @property rule sits in the page or in the card's shadow root. Line 3 sets a typo, siena.
  • 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.

Two halves. On the left, in the shadow root: a tea-card window holds a card, @property --tea-card-accent. Below it, labelled ignored, a crate named registrations holds a faded, crossed-out --tea-card-accent card. Under it: siena gets through. On the right, in the page: a page window holds the same card. An arrow labelled registered goes down to the registrations crate, which holds a --tea-card-accent card. Under it: siena is thrown out.In the shadow roottea-card@property --tea-card-accentignored--tea-card-accentregistrationssiena gets throughIn the pagepage@property --tea-card-accentregistered--tea-card-accentregistrationssiena is thrown out
Every browser ignores @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.
Real-life analogyOne sign on the front door

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: @property in 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: @property inside 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:

The card's file registers its accent, oncePop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • In the tea-card.js tab, lines 2 to 7 register --tea-card-accent with the same three facts. In JavaScript, initial-value is written initialValue.
  • Lines 1 and 8 wrap it in try and catch. A second call for the same name throws an InvalidModificationError: "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 in var() never runs. Exercise 4 shows it.
  • With inherits: false, a value set on body or a section stays there. The card only sees a value set on its own tag. For a styling API, register with inherits: 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:

Four ways to give the tea card a default
Where the default livesWheat on an element around the cardWheat on the tea-card tag16px 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 :hostIt 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 @propertyWheat 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:

tea-card.js's JSDoc, shortened to its custom propertiesJavaScript
/**
 * 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:

The cssProperties list in the kit's custom-elements.jsonJSON
"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: its name, its description, and its default, 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:

The tea card's custom properties
Custom propertyWhat it stylesDefault
--tea-font-displayThe font stack for the tea's name. The page declares the font with @font-face.Georgia, serif
--tea-card-bgThe card's background color.white
--tea-card-accentThe color of the card's border and the tea's name.seagreen
--tea-radiusHow 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:

The kit's cards 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; }  .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>
ResultLoading…
  • In the tea-kit/tea-card.js tab, lines 5 to 9 are the new :host rule. 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-panel in 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 on body or 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.
  • "@property in a component's styles registers the property." No. Every browser ignores it inside a shadow root. Register in the document, or with CSS.registerProperty().
  • "Short names like --color are 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.

Exercise 1 · Warm-uphotpink, then initial

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>
ResultLoading…

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

    Exercise 2 · Warm-upA name with capitals

    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>
    ResultLoading…

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

      Exercise 3 · PracticeThe autumn accent that never arrives

      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>
      ResultLoading…

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

        Exercise 4 · PracticeThe fallback that never runs

        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>
        ResultLoading…

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

          Exercise 5 · ChallengeA registration that stops at the section

          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>
          ResultLoading…

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

            Exercise 6 · ChallengeSquare corners for the badge

            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>
            ResultLoading…

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

              Check your understanding

              For each question, ask: does the property have a usable value here, and where did it come from?

              The custom properties quiz · 7 questionsScore: first tries count
              1. Question 1 of 7The page sets body { --tea-card-bg: wheat; }. Why can a .card inside the card's shadow root read it?

                Choose an answer to see the explanation.

              2. Question 2 of 7What does this page print, with 16px for a background?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <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.

              3. Question 3 of 7What does this page print, with a default on :host?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <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.

              4. Question 4 of 7Which is the best public name for the color of the card's border?

                Choose an answer to see the explanation.

              5. 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.

              6. Question 6 of 7The page registers --tea-card-accent with inherits: false, then sets it on a section around the card. What color is the card's name?

                Choose an answer to see the explanation.

              7. 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-bg has 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.
              • @property adds 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's cssProperties, 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:

              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.

              CompleteFrontend Clear concepts. Working examples.