liveBook · Manning

CSS variable

As explained in Web Component Development with Modern Libraries and Tooling

A CSS property whose value can be defined and reused through a custom identifier, commonly beginning with two hyphens.

A CSS variable, also called a CSS custom property, gives a value a reusable name. In a web component, it can let someone change an internal style without editing the component’s stylesheet. section 3.8.2

Let users choose a component’s text color

Inside a component’s styles, write `p { color: var(--hello-color, purple); }`. The `var()` function uses `--hello-color` when it is defined and `purple` otherwise. Outside the component, `hello-world { --hello-color: red; }` sets the color for that element; `:root { --hello-color: red; }` is another option. Custom properties defined outside a shadow DOM are inherited inside it. section 3.8.2

Two practical uses build on that pattern:

  • Themes: a collection of custom properties can act as design tokens. Changing token values in one place adjusts styling across an app; Web Awesome themes use this approach. section 2.4
  • Reactive styling: a component can update `--font-size` on a paragraph’s `style` attribute while its stylesheet uses `font-size: var(--font-size)`. Lit, Stencil, and FAST examples connect this to a range slider that changes text size. section 5.7 section 6.8

Use a custom property when a style should be configurable from outside a component or driven by a changing component property. Document the properties a component exposes, especially when it offers more than one. section 3.8.2 section 5.7

How Web Component Development with Modern Libraries and Tooling covers it

How deep it goes
Works through var() fallback, shadow DOM inheritance, and slider-driven updates rather than detailing CSS variable resolution rules.
Examples
Uses a configurable paragraph color and a range slider that changes a paragraph’s font size.
What it assumes
Assumes familiarity with HTML elements and CSS rules while introducing custom-property inheritance and var() fallback through examples.
What you can do after
Apply it via CSS var() and element styles to expose component styling options or update styles when component properties change.
How it connects
Connects CSS custom properties to design tokens, themes, shadow DOM, web components, and reactive CSS.

Also explained in

Compare how 7 books explain CSS variable →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Component Development with Modern Libraries and Tooling. The section links point to the parts of the book it draws on.