Sub topic 1
What Design Tokens Are and Why They Help
A design token is a named value for a shared design decision, such as a color, spacing unit, font size, or border radius. Naming the decision lets components use its meaning instead of repeating a raw value.
For example, --color-accent is easier to update consistently than searching for every occurrence of #2563eb. Tokens also make themes possible because one semantic value can change while component rules stay the same.
Prerequisites
This chapter assumes basic CSS selectors, properties, values, the cascade, specificity, and linked stylesheets. You should also understand basic HTML.
Declaring and Using Custom Properties
CSS custom properties are CSS variables whose names begin with two hyphens. Declare them in a rule and read them with var():
:root {
--color-accent: #2563eb;
--space-4: 1rem;
}
.button {
background: var(--color-accent);
padding: var(--space-4);
}:root targets the document's root element, so these values are available throughout the page. The browser substitutes the value of the custom property when it computes the rule.
How Custom Properties Cascade and Inherit
Custom properties follow the cascade. If several matching rules define the same property, the winning declaration comes from normal cascade rules, including origin, importance, specificity, and source order.
They also inherit by default. A value defined on an ancestor is available to descendants unless a descendant defines its own value:
:root {
--color-text: #111827;
}
.card {
color: var(--color-text);
}
.card--muted {
--color-text: #6b7280;
}A muted card and its descendants use the local value. Other elements continue using the root value.
Fallback Values with `var()`
The second argument to var() is a fallback. The browser uses it when the referenced custom property is missing or invalid:
.badge {
padding: var(--badge-padding, 0.75rem);
}Fallbacks can reference another token:
.badge {
padding: var(--badge-padding, var(--space-3, 0.75rem));
}This tries --badge-padding, then --space-3, then 0.75rem.
Exercise
A component needs a local padding of 0.5rem, while other cards use 1rem. How can you override the token without changing the shared rule?
Show answer
Define --card-padding: 1rem on .card, then redefine --card-padding: 0.5rem on .card--compact.