A CSS variable, or custom property, holds a value that CSS declarations reuse through var(). Define shared design tokens on :root, then override them on a theme class, container, or component. Values inherit through the DOM, so descendants can respond to a new theme without rewriting their rules. section 4.1.2
A theme with shared tokens
Define :root { --brand: #5d4037; } and use background: var(--brand) on a button. A class such as .theme-matcha { --brand: #2e7d32; } on html changes the inherited brand color. Prefer a name like --brand over a literal color name so the token remains meaningful after a redesign. section 4.1.2
Keep each styling responsibility explicit:
- Use shared tokens for colors, spacing, typography, radius, and timing; give component-specific sizing or state its own variables. section 4.1.2
- Use prefers-color-scheme for automatic theme defaults, and a class for a chosen theme. A stored user selection can determine which class goes on html. section 4.1.2
- When styling from JavaScript, toggle classes or data attributes for state. Use style.setProperty() for a dynamic custom-property value; inspect the result with getComputedStyle(). section 6.2.12
Custom properties also provide a styling interface for a web component. Page CSS can set tokens on its host; shadow-DOM CSS can consume them with var() while defining defaults on :host. Expose only the tokens consumers should change, and document them alongside other public component styling options. For slotted content, a token can control a styled slot container when direct styling is limited. section 7.12.2 section 8.5.2
Listing 7.7 Implementing variable color definition for StarRatingComponent
/* this goes in the custom element CSS declaration (shadow DOM) */
:host {
display: inline-block;
--stars-inactive-color: silver;
--stars-active-color: orangered;
}
ul {
list-style: none;
padding: 0;
display: flex;
}
li {
color: var(--stars-inactive-color);
}
li.active {
color: var(--stars-active-color);
}
The component gives active and inactive star colors default values on :host, then uses those tokens inside its shadow-DOM styles. section 7.12.2






