Sub topic 9
Keeping Styles Consistent with Custom Properties
This chapter assumes you can write HTML and CSS selectors, set font-size, font-weight, and color, and have seen the type scale from the earlier chapters. Here you will turn that scale into a small set of named values called design tokens, so headings, body text, captions, and labels stay consistent as the stylesheet grows.
Why hard-coded values drift
Suppose a stylesheet sets caption text to 0.875rem in one rule and 0.9rem in another. Neither is wrong on its own. But after a few months the page has five slightly different "small" sizes, and nobody remembers which was intended. The hierarchy you designed gets blurry because the values that express it are scattered.
The fix is to define each decision once, give it a name, and refer to the name everywhere. In CSS, the tool for this is the custom property.
What a custom property is
A custom property is a CSS variable whose name starts with two dashes. You declare it like any other property and read it with the var() function.
:root {
--text-base: 1rem;
}
p {
font-size: var(--text-base);
}Three facts explain most of how custom properties behave:
- They are ordinary CSS declarations, so they follow the cascade and inherit down the tree.
- They are resolved at runtime in the browser. Unlike variables in a preprocessor such as Sass, they can change after the page loads, and they can differ between parts of the page.
- Names are case-sensitive.
--Text-baseand--text-baseare different properties.
:root matches the html element. Declaring tokens there makes them available to the whole document through inheritance.
Tokens for the type scale
A token is a named value that encodes a design decision. For text hierarchy, you need two groups: sizes and line heights.
:root {
/* Sizes: the type scale */
--text-sm: 0.875rem;
--text-base: 1rem;
--text-lg: 1.25rem;
--text-xl: 1.5rem;
--text-2xl: 2rem;
/* Line heights */
--leading-body: 1.5;
--leading-heading: 1.2;
}The sizes use rem, which is relative to the root font size. Because the browser's default root size follows the user's preference, text built on rem tokens still respects people who raise their default font size. Line heights are unitless numbers, so each element multiplies its own font size by the number. A unitless value avoids the problem where a fixed line height inherited from a parent fits the parent's text but not a child with a larger font.
Now the element rules read as statements about roles:
body {
font-size: var(--text-base);
line-height: var(--leading-body);
}
h1 { font-size: var(--text-2xl); line-height: var(--leading-heading); }
h2 { font-size: var(--text-xl); line-height: var(--leading-heading); }
h3 { font-size: var(--text-lg); line-height: var(--leading-heading); }
figcaption {
font-size: var(--text-sm);
}If you later decide the whole scale is a bit too small, you change values in one block. Every rule that uses the tokens follows.
Naming tokens: by scale position or by role
There are two common naming styles, and they solve different problems.
| Style | Example | Strength | Weakness |
|---|---|---|---|
| By scale position | `--text-lg` | Describes the value's place in the scale. Easy to extend. | Says nothing about where it is used. |
| By role | `--heading-size`, `--caption-size` | Says what the value is for. Changing a role is a single edit. | The set of names grows with each new role. |
A practical approach uses both layers. The scale tokens hold raw values. Role tokens point to scale tokens:
:root {
--text-sm: 0.875rem;
--text-base: 1rem;
--text-lg: 1.25rem;
--text-xl: 1.5rem;
--text-2xl: 2rem;
--size-h1: var(--text-2xl);
--size-h2: var(--text-xl);
--size-h3: var(--text-lg);
--size-body: var(--text-base);
--size-caption: var(--text-sm);
--size-label: var(--text-base);
}
h1 { font-size: var(--size-h1); }
h2 { font-size: var(--size-h2); }
h3 { font-size: var(--size-h3); }
figcaption { font-size: var(--size-caption); }
label { font-size: var(--size-label); }Now a design change such as "labels should be slightly smaller" means editing one line, --size-label: var(--text-sm);, without touching the label rule or the scale.
Do not add a role layer on day one for a three-page site. It is extra indirection. Add it when you notice the same scale value standing in for different roles that you may want to change independently.
Fallback values
var() accepts a second argument that is used when the property is not defined.
figcaption {
font-size: var(--size-caption, 0.875rem);
}Fallbacks help when a component is reused in a page that might not load your tokens. Use them sparingly. A fallback duplicates the value, which brings back the drift you were trying to avoid.
Tokens for color and weight
Text hierarchy depends on more than size. Weight and color also separate roles, and they benefit from the same treatment.
:root {
--weight-regular: 400;
--weight-semibold: 600;
--weight-bold: 700;
--color-text: #1a1a1a;
--color-text-muted: #595959;
}
h1, h2, h3 { font-weight: var(--weight-bold); }
label {
font-weight: var(--weight-semibold);
}
figcaption {
color: var(--color-text-muted);
}Keeping muted text color in a token has an accessibility benefit. You check the contrast of --color-text-muted once against your background, and every caption inherits the result. Small text such as captions needs a contrast ratio of at least 4.5:1 under WCAG, and #595959 on white passes. If you change the token, recheck it.
Tokens and the cascade: scoped overrides
Because custom properties inherit, you can redefine a token inside a part of the page and everything within it picks up the new value.
<main>
<h2>Gear</h2>
<p>Start with footwear, then add layers.</p>
</main>
<aside class="compact">
<h2>Quick tips</h2>
<p>Break in new boots before the trip.</p>
</aside>:root {
--text-base: 1rem;
--text-xl: 1.5rem;
}
h2 { font-size: var(--text-xl); }
p { font-size: var(--text-base); }
.compact {
--text-base: 0.9375rem;
--text-xl: 1.25rem;
}The h2 and p rules never mention .compact. Inside the aside, the tokens resolve to the smaller values because the nearest declaration wins. This is a clean way to make a sidebar denser without writing separate selectors for each element.
One caution: a token override changes every use of that token in the subtree, including uses you did not think about. If --text-base also sizes your form inputs, they shrink too. Override role tokens when you can, because they have a narrower effect.
Common errors
These problems show up repeatedly with custom properties.
- Using
var()in a media query condition. Custom properties cannot be used inside the condition of@media.@media (min-width: var(--bp))does not work. Write the number directly there, and use tokens inside the rules. - Forgetting that an invalid value fails late. If
--text-baseis set to1 rem(with a space), the declarationfont-size: var(--text-base)becomes invalid at computed-value time. The property then falls back to its inherited or initial value rather than to your earlier rule. Check the computed value in dev tools when a size looks wrong. - Typos in names.
var(--text-bsae)refers to nothing. Without a fallback, the declaration is invalid and the property is treated as unset. A fallback can hide the typo, so an unexpected "correct-looking" size is worth a second look. - Declaring tokens on a selector that does not reach the element. Tokens declared on
.cardare not visible to afigcaptionoutside.card. Put shared tokens on:root. - Computing with unitless tokens.
--leading-body: 1.5is fine forline-height. Butcalc(var(--text-base) * 1.5)works only when the token has a unit. Multiplying a length by a number is valid. Multiplying two lengths is not.
Tokens with `calc()` and `clamp()`
Tokens combine with math functions. A heading size can be derived from a base value, and the responsive clamp() you will meet in the next chapter can be stored as a token too.
:root {
--text-base: 1rem;
--scale-ratio: 1.25;
--text-lg: calc(var(--text-base) * var(--scale-ratio));
--text-xl: calc(var(--text-lg) * var(--scale-ratio));
--text-display: clamp(1.75rem, 1.2rem + 2vw, 3rem);
}
h1 {
font-size: var(--text-display);
}Here --scale-ratio is a plain number and --text-base has a unit, so the multiplication is valid. This approach produces a modular scale: each step is the previous one times a fixed ratio. It is tidy, but computed values such as 1.5625rem are harder to read in dev tools than hand-picked ones. Choose derived values when you want a mathematically even scale, and hand-picked values when you want round numbers.
Where to put the tokens
Keep tokens at the top of your main stylesheet, or in a separate file loaded first. Group them by kind, with a short comment for each group. Everything else in the stylesheet should read them, not repeat them.
A quick audit finds leaks. Search your CSS for raw font-size, font-weight, and line-height values outside the token block. Each hit is either a missing token or a deliberate exception that deserves a comment.
A complete example
This example puts the tokens to work across all four text roles from this tutorial: a heading, body text, a caption, and a form label.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Trail Guide</title>
<style>
:root {
--text-sm: 0.875rem;
--text-base: 1rem;
--text-lg: 1.25rem;
--text-2xl: 2rem;
--leading-body: 1.5;
--leading-heading: 1.2;
--weight-semibold: 600;
--weight-bold: 700;
--color-text: #1a1a1a;
--color-text-muted: #595959;
--size-h1: var(--text-2xl);
--size-h2: var(--text-lg);
--size-body: var(--text-base);
--size-caption: var(--text-sm);
--size-label: var(--text-base);
}
body {
font-size: var(--size-body);
line-height: var(--leading-body);
color: var(--color-text);
max-width: 65ch;
margin: 2rem auto;
padding: 0 1rem;
}
h1, h2 {
font-weight: var(--weight-bold);
line-height: var(--leading-heading);
}
h1 { font-size: var(--size-h1); }
h2 { font-size: var(--size-h2); }
figcaption {
font-size: var(--size-caption);
color: var(--color-text-muted);
}
label {
display: block;
font-size: var(--size-label);
font-weight: var(--weight-semibold);
margin-bottom: 0.25rem;
}
input {
font: inherit;
padding: 0.5rem;
}
</style>
</head>
<body>
<h1>Trail Guide</h1>
<p>A short introduction to planning a multi-day hike.</p>
<h2>Gear</h2>
<figure>
<img src="boots.jpg" alt="A pair of leather hiking boots on a rock">
<figcaption>Leather boots after a week on the trail.</figcaption>
</figure>
<h2>Get the checklist</h2>
<label for="email">Email address</label>
<input id="email" name="email" type="email" autocomplete="email">
</body>
</html>To see the system work, change --size-caption to var(--text-base) and reload. Only the caption changes. The scale, the headings, and the label are untouched.
How the pieces connect
Reading the diagram from top to bottom: you edit the top layer to change the whole scale, the middle layer to change what a role means, and the bottom layer almost never.
Review checklist
- Every font size, line height, weight, and text color in your rules comes from a token, except documented exceptions.
- Sizes use
rem, line heights are unitless, and tokens are declared on:root. - Role tokens exist only where you need to change a role independently.
- Muted text colors are checked for contrast once, at the token.
- Scoped overrides change role tokens where possible, not scale tokens.
- No
var()appears inside an@mediacondition.
Exercise
A stylesheet declares --text-base: 1rem; on :root, then uses p { font-size: var(--text-base); } and input { font-size: var(--text-base); }. You add .sidebar { --text-base: 0.875rem; } to make sidebar paragraphs smaller. What else changes, and how would you avoid it?
Show answer
Every element inside .sidebar that reads --text-base gets 0.875rem, including any input in the sidebar. To avoid this, introduce role tokens such as --size-body and --size-input, both set to var(--text-base) on :root. Override only --size-body inside .sidebar, and make the paragraph rule read --size-body. Inputs keep reading --size-input and stay the same size.
Exercise
Why does font-size: var(--text-base) fall back to an inherited size, rather than your earlier rule, when --text-base is defined as 1 rem (with a space)?
Show answer
The value 1 rem is not a valid length, but the browser cannot know that when it parses --text-base, because custom properties accept almost any value. The error only appears when var() is substituted into font-size, which is computed-value time. At that point the declaration is "invalid at computed-value time", so the property behaves as if unset. font-size is inherited, so it takes the parent's size. The earlier rule is not restored because the invalid declaration still won the cascade.
Exercise
You define --text-base: 1rem; and --scale-ratio: 1.25;. Write a token --text-lg that is one step larger on the scale, then say why calc(var(--text-base) * var(--text-base)) would not work.
Show answer
--text-lg: calc(var(--text-base) * var(--scale-ratio)); gives 1.25rem. In calc(), you can multiply a length by a plain number, but you cannot multiply two lengths, because the result would be a squared unit that no property accepts. var(--text-base) * var(--text-base) multiplies two lengths, so the declaration is invalid.