Sub topic 9
Centralize colors and spacing with custom properties
The navigation bar from the earlier chapters repeats the same colors and spacing values in several rules. This chapter moves them into CSS custom properties, so each value is defined once and the bar can be themed from a single place.
This chapter assumes you can write basic HTML and CSS selectors and understand the box model (margin, padding, border). It also assumes you have the nav bar markup and the Flexbox, link, hover, focus and current-page rules from the previous chapters.
Why repeated values cause trouble
Look at the rules so far. The color #38bdf8 appears in the focus outline and in the current-page border. The color #1f2937 appears in the bar and again in the submenu. If you want to change the accent color, you must find every copy and edit it. Miss one and the bar has two accent colors.
Spacing has the same problem. The link padding of 0.75rem 1rem is a decision about how dense the bar feels. That decision should live in one place, not be scattered across rules.
A custom property is a CSS value you name yourself and reuse. It is sometimes called a CSS variable. Unlike variables in Sass or Less, it exists in the browser at run time, which gives it abilities a build-time variable lacks. We return to that later.
Declare a property and use it
A custom property name starts with two hyphens. You declare it like any other property, inside a rule. You read it with the var() function.
:root {
--nav-accent: #38bdf8;
}
.nav-list a:focus-visible {
outline: 2px solid var(--nav-accent);
}The :root selector matches the html element. Declaring a property there makes it available to every element in the page, because custom properties are inherited by default.
Three details are worth knowing:
- Names are case-sensitive.
--Nav-Accentand--nav-accentare different properties. - The value can be anything that is valid as a token sequence: a color, a length, a number, even a whole
bordershorthand. The browser does not check the value when you declare it. It checks only whenvar()is substituted into a real property. var()accepts a second argument, a fallback, which we cover below.
Refactor the navigation bar
Start by choosing which values deserve a name. A useful rule is to name decisions, not raw values. --nav-bg says what the color is for. --gray-800 says only what it looks like, and it stops being accurate the day you change the theme.
:root {
--nav-bg: #1f2937;
--nav-bg-hover: #374151;
--nav-bg-current: #111827;
--nav-text: #ffffff;
--nav-accent: #38bdf8;
--space-1: 0.25rem;
--space-3: 0.75rem;
--space-4: 1rem;
}The spacing names are a scale, not a description of use. --space-1 is a quarter of a rem and --space-4 is one rem. Scale names let one value serve the gap, the padding and the submenu without implying that those uses are tied together.
Now rewrite the layout rules from the earlier chapters to use the properties:
.nav-list {
display: flex;
gap: var(--space-1);
margin: 0;
padding: 0;
list-style: none;
background: var(--nav-bg);
}
.nav-list a {
display: block;
padding: var(--space-3) var(--space-4);
color: var(--nav-text);
text-decoration: none;
}Then the state rules:
.nav-list a:hover,
.nav-list a:focus-visible {
background: var(--nav-bg-hover);
}
.nav-list a:focus-visible {
outline: 2px solid var(--nav-accent);
outline-offset: -2px;
}
.nav-list a[aria-current="page"] {
background: var(--nav-bg-current);
border-bottom: 3px solid var(--nav-accent);
}The dropdown from the later chapter can share the same properties:
.submenu {
background: var(--nav-bg);
}The page now looks exactly as it did before. The change is in the source. To restyle the bar, you edit the :root block and nothing else.
How scope and inheritance work
A custom property behaves like an inherited property such as color. An element gets the value declared on itself, or else the value from its nearest ancestor that declares it. This is the feature that lets you theme part of a page.
Suppose one page has a light bar. You can override only the properties that change, on the nav element:
.theme-light {
--nav-bg: #e5e7eb;
--nav-bg-hover: #d1d5db;
--nav-bg-current: #f9fafb;
--nav-text: #111827;
--nav-accent: #0369a1;
}<nav class="theme-light" aria-label="Main">
<ul class="nav-list" id="nav-list">
<li><a href="/" aria-current="page">Home</a></li>
<li><a href="/products">Products</a></li>
</ul>
</nav>The .nav-list rule still says background: var(--nav-bg). The browser resolves var() on each element using the values that element inherits. Inside the nav it gets the light value, and everywhere else it gets the :root value. You did not write a single new layout rule.
Because the substitution happens at run time, you can also respond to user preferences. Here the dark values are the default and a media query swaps in light values for people whose system is set to a light appearance:
@media (prefers-color-scheme: light) {
:root {
--nav-bg: #e5e7eb;
--nav-bg-hover: #d1d5db;
--nav-bg-current: #f9fafb;
--nav-text: #111827;
--nav-accent: #0369a1;
}
}Place this block after the main :root block. Both selectors have the same specificity, so the later one wins when the media query matches.
Fallback values
var() takes an optional second argument that is used when the property is not defined:
.nav-list a {
color: var(--nav-text, #ffffff);
}The fallback applies only when the property is missing or invalid at computed-value time. It does not apply when the property is defined and merely looks wrong to you. The fallback can itself contain var(), so var(--nav-accent, var(--brand, #38bdf8)) is legal. Use fallbacks for components that may be dropped into pages that do not define your properties. Inside a single stylesheet that you control, they mostly hide typos.
Doing arithmetic with properties
You can combine properties with calc(). A common case is deriving sizes from one base value:
:root {
--space-unit: 0.25rem;
}
.nav-list {
gap: var(--space-unit);
}
.nav-list a {
padding: calc(var(--space-unit) * 3) calc(var(--space-unit) * 4);
}This works because --space-unit holds a length with its unit. If you store a bare number such as --space-unit: 4 you must multiply it by a unit, as in calc(var(--space-unit) * 1px). You cannot write var(--space-unit)px, because the substitution produces two separate tokens, not one length.
Changing a property from JavaScript
Because custom properties are live, a script can change one and every rule that reads it updates:
const nav = document.querySelector('nav');
nav.style.setProperty('--nav-accent', '#f472b6');
console.log(getComputedStyle(nav).getPropertyValue('--nav-accent'));setProperty is required here. Writing nav.style['--nav-accent'] = ... does not work for custom properties. The second line reads the value back. Note that getPropertyValue returns the value as written, and it may include leading whitespace in some browsers, so trim it before comparing.
Common errors
A mistake in a custom property rarely produces a visible error message. Check these first when something looks wrong.
| Symptom | Likely cause | Fix |
|---|---|---|
| The property is ignored completely | Missing the leading `--`, as in `nav-bg: #111` | Write `--nav-bg: #111` |
| A color has no effect and the element looks unstyled | Typo in the name inside `var()`, such as `var(--nav-bgg)` | Check the spelling and case in dev tools |
| `padding` is ignored entirely | The property holds an invalid value for that use, such as `--space-3: red` | Check the computed value in dev tools |
| Override on `nav` has no effect | The properties are declared in a rule that targets the inner `.nav-list` or the links themselves | Declare overrides on an ancestor of every element that reads them, or on the element itself |
| Media query using `var()` does nothing | Custom properties cannot be used inside media query conditions | Write the literal value, such as `40rem` |
The third row deserves explanation. When var() refers to a property that is missing or holds a value that does not fit, the declaration becomes invalid at computed-value time. The browser does not fall back to the previous rule in the cascade. It treats the property as unset. For padding that means 0. For background it means transparent. This is why a typo can make a button look as if all its styles disappeared.
Custom properties compared with preprocessor variables
If you have used Sass, $accent: #38bdf8; looks similar. The differences decide which tool to use:
- A Sass variable is replaced during the build. The browser never sees it, so it cannot change after the page loads.
- A custom property is part of the cascade. It inherits, it can be overridden per element, and a script or a media query can change it.
- Sass can use variables in places CSS cannot, such as media query conditions and selector names.
For a navigation bar, custom properties are the better fit, because theming and the dark or light switch depend on run-time changes. The two tools can also be used together.
Choosing what to name
Not every number needs a property. Too many names makes the stylesheet harder to read than the repeated values it replaced. A practical test is to ask whether you would change the value in one place and expect every use to follow. The accent color passes. The 3px current-page border thickness might pass if you reuse it for other highlights. The 12rem minimum width of the submenu probably stays as a plain value, because only one rule uses it.
Group the declarations by purpose, with colors first and spacing second, and keep them in one :root block near the top of the file. That block then works as the control panel for the bar.
Exercise
A page defines --nav-accent: #38bdf8; on :root. The nav element has the class promo, and you add the rule .promo { --nav-accent: #f472b6; }. The links inside use border-bottom: 3px solid var(--nav-accent);. Which color do the links inside .promo get, and what happens to links elsewhere on the page? Then say what happens to the border if a link rule contains the typo var(--nav-acent) with no fallback.
Show answer
Links inside .promo get #f472b6, because each element resolves var() from the nearest ancestor that declares the property, and .promo is closer than :root. Links elsewhere keep #38bdf8. With the typo, --nav-acent is not defined, so the declaration is invalid at computed-value time and border-bottom becomes unset, which means no border. A fallback such as var(--nav-acent, #38bdf8) would hide the typo but still render a border.
Exercise
Add a --nav-height: 3rem; property and use it so the bar and its submenu offset stay in sync. Which property in the earlier chapters would read it, and why can you not use it in the @media condition?
Show answer
Set min-height: var(--nav-height); on .nav-list, and use top: var(--nav-height); for the submenu in place of top: 100% if the bar height is fixed. You can also use it for the scroll-padding-top of the page so that anchor links are not hidden under a sticky bar. It cannot go in the @media condition because media queries are evaluated before custom properties are resolved, so the condition needs a literal value such as 40rem.