Skip to main content
XenonStack

Data Visualization

XenonStack Blog CSS Custom Properties: Design Tokens and Theming Guide

and | Published | Updated

CSS Custom Properties: Design Tokens and Theming Guide
13:13

Key takeaway

  • CSS custom properties explained with MDN and W3C sources: syntax, fallbacks, @property, dark mode, container queries and token governance for teams.

What are CSS custom properties and when should an enterprise team use them?

CSS custom properties, also called CSS variables, are author-defined properties that start with two dashes, such as --brand-color, and are read with var(--brand-color). They inherit through the DOM, follow the cascade and are resolved by the browser at runtime, so one change at a theme or component level reaches every place that uses the value (MDN).

For a team shipping one product, they remove repeated values. For an organisation with several products, they are the delivery layer of a design system: tokens such as colour, spacing and type scale become named, inheritable values that dark mode, brand variants and component libraries can all share. This guide covers the syntax, the traps, theming, container queries and how to govern a shared token set across teams. For related fundamentals, see our guides on fluid typography with clamp() and class versus ID selectors.

How do you declare and use a custom property?

Declare the property inside a rule and read it with var(). Names must begin with two dashes and are case sensitive, so --Brand and --brand are different properties (MDN). The :root selector is the usual place for global values, and a component selector is the place for local ones.

:root {
  --brand-color: #0b5fff;
  --space-4: 1rem;
}

.card {
  --card-padding: var(--space-4);
  padding: var(--card-padding);
  border-top: 4px solid var(--brand-color);
}

Custom properties always inherit from the parent, subject to the cascade, and the browser computes them where they are used. A property set on .card is therefore available to that card and its descendants only. Setting variables at the lowest scope that needs them is often easier to read than putting everything on :root.

What are the rules for fallbacks and invalid values?

var() takes the property name first. Everything after the first comma is the fallback, so var(--fonts, Helvetica, Arial, sans-serif) falls back to the whole font list. To chain fallbacks, nest another var(): var(--a, var(--b, red)). MDN notes that nested fallbacks have a parsing cost, and that fallbacks do not help browsers that lack custom property support at all.

The W3C module defines the guaranteed-invalid value as the initial value of every custom property, and a fallback is used when the referenced property holds it. A different problem arises when the property is set but its value is wrong for the property that uses it, for example --text-color: 16px used in color. The declaration is then invalid at computed-value time, and the browser uses the inherited value if the property inherits, otherwise its initial value (MDN). Custom properties are also subject to cycles: any properties that reference each other in a loop become invalid (CSS Custom Properties for Cascading Variables Module Level 1, shown as a W3C Candidate Recommendation Snapshot dated 16 June 2022 when we read it).

SituationWhat the browser doesWhat to do
Property not defined, fallback givenUses the fallbackProvide a fallback only where a default is meaningful
Property not defined, no fallbackDeclaration invalid at computed-value time; inherited or initial value usedRegister the property with @property, or add a fallback
Property set to a value of the wrong typeDeclaration invalid at computed-value time; fallback is not usedRegister the property with a syntax so bad values fall back to initial-value
Two properties reference each otherBoth become invalidReview token aliases for loops in code review

What does @property add?

The @property rule registers a custom property with a type, an inheritance setting and an initial value. According to MDN, inherits is required, initial-value is required unless the syntax is "*", and the initial value must be computationally independent, so 10px is valid and 3em is not. It is Baseline 2024, newly available since July 2024, so check older browser targets first.

@property --brand-color {
  syntax: "<color>";
  inherits: true;
  initial-value: #0b5fff;
}

Registration gives a platform team three things that plain custom properties lack: type checking, a safe default when a consumer supplies a bad value, and the ability to animate the value, such as a gradient stop or progress percentage.

How should a shared token set be structured?

A common structure uses three layers. Primitive tokens hold raw values, semantic tokens say what a value is for, and component tokens bind semantic tokens to one component. Components read only the layer above them, which is what makes a rebrand or a dark theme a change at one layer.

Two-column diagram: token layers (primitive, semantic, component, themes) mapped to governance controls (owner, change classes, registered types, cascade layers).
LayerExampleWho may change itConsumed by
Primitive--blue-600: #0b5fffDesign system ownersSemantic tokens only
Semantic--color-action: var(--blue-600)Design system owners, with reviewComponents and product teams
Component--button-bg: var(--color-action)Component ownerThat component only

The Design Tokens Community Group released its first stable Design Tokens Format Module, version 2025.10, on 28 October 2025. It is a Community Group final report and not a W3C Recommendation, so treat it as an interoperability aid between design tools and build pipelines, and confirm tool support on the group page before committing to it (W3C Design Tokens Community Group).

How do you implement dark mode and theming?

Two native mechanisms are available. The prefers-color-scheme media feature reports the user's light or dark preference and is Baseline widely available since January 2020 (MDN). The light-dark() function returns one of two colours depending on the scheme; it needs color-scheme: light dark on the root and is Baseline 2024, newly available since May 2024 (MDN).

:root {
  color-scheme: light dark;
  --surface: light-dark(#ffffff, #14181f);
  --text: light-dark(#14181f, #f2f4f8);
}
body { background: var(--surface); color: var(--text); }
ApproachWhen it fitsTrade-off
prefers-color-scheme media queryFollow the operating system setting onlyNo in-page toggle without extra code
light-dark() with color-schemeColour tokens that differ only by scheme; least codeNewer browser baseline; colours and images only
Data attribute on the root elementA user-controlled toggle or per-brand themesNeeds JavaScript and a stored preference
CombinationRespect the system by default, allow overrideMore states to test

MDN advises against forcing a scheme on a real site because it overrides the user's preference. Read values from script with getComputedStyle(el).getPropertyValue("--x") and write them with el.style.setProperty("--x", value).

How do custom properties work with container queries?

MDN states that var() cannot be used in media or container query conditions, so a breakpoint cannot be a variable. Container style queries go the other way and test a custom property on a container: @container style(--theme: dark). In the plain syntax the left side must be the property name without var(); the range syntax, for example style(--n >= 3), resolves var() references. For an unregistered property the valueless form is always true, and equivalent values such as blue and #0000ff match only if the property is registered with a colour syntax. MDN noted in February 2024 that style queries work only with custom properties, so check the compatibility table for current support.

Size queries use container-type: inline-size on a wrapper, which lets a component respond to the space it is given. A practical pattern is to keep spacing tokens in custom properties, and let the container decide which token the component uses.

How do you govern a token set across teams?

Technical choices keep a token set consistent; governance keeps it trusted. Use these controls.

ControlWhat it means in practiceEvidence to keep
Named ownerOne team owns primitive and semantic tokens; product teams own component tokensOwnership file in the repository
Change classesAdditive, value change, rename, removal, each with a review pathPull request labels
Deprecation windowOld token kept as an alias to the new one for an agreed periodRelease notes and a removal date
Cascade layersDeclare @layer reset, tokens, base, components, overrides; once so precedence does not depend on selector specificityLayer order in the shared stylesheet
Naming ruleNames say purpose, not value: --color-action, not --blueLint rule
Registered typesRegister critical tokens with @property so bad values fail safe@property rules in the shared package

According to MDN, @layer is Baseline widely available since March 2022, and for normal declarations unlayered styles override all layered ones, so keep third-party and legacy CSS inside a layer. The same discipline of versioned policy and decision traces matters for AI-assisted UI work: ElixirData Context OS keeps governed context, versioned policy and decision traces in one decision layer above AI agents, and ElixirClaw is an agentic OS platform to build, orchestrate and govern AI agents and automation workflows while keeping humans in control, both according to their own sites.

When should you not use custom properties?

CaseBetter choiceReason
A value that never changes and is used onceA literal valueIndirection adds reading cost
A breakpointA literal in the media or container queryvar() is not allowed in query conditions (MDN)
Build-time logic such as loops and maths over many valuesA preprocessor or token build stepCustom properties are resolved at runtime
Selector or property namesNot possiblevar() cannot be used for them (MDN)
Very deep chains of aliases and nested fallbacksFlatten the chainHarder to debug; nested fallbacks have a parsing cost (MDN)

What is a safe adoption sequence?

StepActionExit check
1Audit repeated colours, spacing and type valuesList of values used more than three times
2Define primitive and semantic tokensEvery semantic token has an owner
3Replace literals in two pilot componentsNo visual regression in review
4Add dark mode and registered critical tokensBoth schemes pass contrast review
5Publish the layer order and change classesTeams can raise a token change without a meeting
6Add a lint rule for raw valuesNew code uses tokens

For teams splitting a front end across applications, see our guide to micro frontend architecture, where a shared token package is often the first thing teams agree on, and how the browser renders pages for how style resolution fits into the render tree.

To map one token or UI decision your teams and agents should make, and the context and policy it depends on, book a Context Workshop. See what happens in the workshop.

Frequently asked questions

What are CSS custom properties?

CSS custom properties, often called CSS variables, are author-defined properties whose names start with two dashes, such as --brand-color. You read them with the var() function, they inherit down the DOM tree, and the browser resolves them at runtime, unlike Sass or Less variables, which compile away.

Are CSS custom properties the same as design tokens?

No. A design token is a named design decision stored in a platform-neutral format. A CSS custom property is one way to deliver that token to a browser. The Design Tokens Community Group published its first stable format version, 2025.10, on 28 October 2025, as a Community Group report and not a W3C Recommendation.

Why does my var() fallback not apply?

A fallback is used when the referenced property is not defined. If the property is defined but holds a value that is wrong for the property using it, the declaration becomes invalid at computed-value time and the browser uses the inherited or initial value instead. Registering the property with @property and a syntax guards against this.

Can I use var() inside a media query or container query?

MDN states that var() cannot be used in media or container query conditions. Container style queries can test a custom property directly, for example @container style(--theme: dark), and the range syntax can resolve var() references. Check the MDN compatibility table before relying on style queries.

What is the safest way to implement dark mode with custom properties?

Declare colour-scheme support with color-scheme: light dark, set semantic tokens once, and use either light-dark() or a prefers-color-scheme media query to switch them. Keep component code reading only semantic tokens so that a theme change touches one layer.

Follow XenonStack on LinkedIn: XenonStack on LinkedIn for new guides on agentic AI, data and platform engineering.

Table of Contents

navdeep-singh-gill

Navdeep Singh Gill

Global CEO and Founder of XenonStack

LinkedIn profile

Navdeep Singh Gill is serving as Chief Executive Officer and Product Architect at XenonStack. He holds expertise in building SaaS Platform for Decentralised Big Data management and Governance, AI Marketplace for Operationalising and Scaling. His incredible experience in AI Technologies and Big Data Engineering thrills him to write about different use cases and its approach to solutions.

Get the latest articles in your inbox

Subscribe Now

Interested in solving your challenges with the XenonStack team?
Get Started

Tell us about you and your priorities so we can prepare the right conversation. It takes about 2 minutes.

Please Select your Industry
Banking
Fintech
Payment Providers
Wealth Management
Discrete Manufacturing
Semiconductor
Machinery Manufacturing / Automation
Appliances / Electrical / Electronics
Elevator Manufacturing
Defense & Space Manufacturing
Computers & Electronics / Industrial Machinery
Motor Vehicle Manufacturing
Food and Beverages
Distillery & Wines
Beverages
Shipping
Logistics
Mobility (EV / Public Transport)
Energy & Utilities
Hospitality
Digital Gaming Platforms
SportsTech with AI
Public Safety - Explosives
Public Safety - Firefighting
Public Safety - Surveillance
Public Safety - Others
Media Platforms
City Operations
Airlines & Aviation
Defense Warfare & Drones
Robotics Engineering
Drones Manufacturing
AI Labs for Colleges
AI MSP / Quantum / AGI Institutes
Retail Apparel and Fashion

Continue