Lesson 11
15 min
Define and reuse values with CSS custom properties.
Definition
A CSS variable (officially a custom property) is a named value, declared once with a name starting with two dashes, then reused as often as you like with the var() function. Unlike preprocessor variables, it is live in the browser: its value can change depending on the context, a state or a script.
CSS variables let you define a value once and reuse it everywhere — ideal for a consistent color palette or regular spacing.
:root {
--color-primary: #6d28d9;
--color-text: #1e293b;
--spacing: 16px;
--border-radius: 8px;
}
.button {
background-color: var(--color-primary);
padding: var(--spacing);
border-radius: var(--border-radius);
}
.title {
color: var(--color-text);
}:root represents the document’s root element (the same element as html, with higher specificity): variables declared there are available everywhere on the page.--variable-name.var(--variable-name) function.A good name describes the role of the value rather than its shade:--color-primary stays accurate the day the brand switches from purple to blue, whereas --purple becomes misleading. Names are case-sensitive:--Bg and --bg are two different variables.
--border-radius.--color-…, --space-…, --shadow-….--text-secondary over --gray-600 in your components.The main advantage: changing a single line updates the whole page. Without variables, you would have to search for and replace every occurrence of the color throughout the file.
Without a variable
.button { background: #6d28d9; }
.link { color: #6d28d9; }
.badge { border-color: #6d28d9; }
/* To change the color, you have to
edit 3 different places */With a variable
:root { --primary: #6d28d9; }
.button { background: var(--primary); }
.link { color: var(--primary); }
.badge { border-color: var(--primary); }
/* Only one place to edit */var() accepts a second parameter, used if the variable doesn’t exist.
.element {
color: var(--color-text, #333); /* uses #333 if --color-text is not defined */
}The fallback value can itself be another variable, which lets you chain several levels of fallback: the browser tries each option in order. It’s handy for a component that accepts optional customization while keeping a default style consistent with the rest of the site.
.button {
/* 1) --button-bg if defined, 2) otherwise --color-primary, 3) otherwise #6d28d9 */
background-color: var(--button-bg, var(--color-primary, #6d28d9));
}A variable follows the rules of inheritance: declared on an element, it is available to all of its descendants, but not outside of it. That’s why global variables are placed in :root, at the very top of the tree, while variables specific to a component are declared on its selector.
:root {
--space: 16px; /* available everywhere on the page */
}
.card {
--card-bg: #f8fafc; /* available only inside .card and its children */
background-color: var(--card-bg);
padding: var(--space);
}
.menu {
background-color: var(--card-bg); /* useless: variable unknown here, no effect */
}Variables pair very well with calc(): you define a base value, then derive others from it by multiplication or addition. To change all the spacing at once, you then only need to edit a single variable.
:root {
--space: 8px;
--space-medium: calc(var(--space) * 2); /* 16px */
--space-large: calc(var(--space) * 4); /* 32px */
}
.section {
padding: var(--space-large);
margin-bottom: var(--space-medium);
}A variable can be redefined inside a more specific selector, which changes its value only in that portion of the page — very handy for theme variants.
:root {
--badge-color: #6d28d9;
}
.badge {
background-color: var(--badge-color);
}
.badge.success {
--badge-color: #059669; /* overrides the variable, for this badge only */
}
.badge.error {
--badge-color: #dc2626;
}By grouping colors, spacing, typography, radii and shadows as variables, you get what design teams call design tokens: a shared vocabulary that guarantees the visual consistency of the whole site.
:root {
/* Colors */
--color-primary: #6d28d9;
--color-background: #ffffff;
--color-text: #1e293b;
/* Typography */
--font-text: system-ui, sans-serif;
--font-size-base: 1rem;
/* Shapes */
--radius: 8px;
--shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
.card {
font-family: var(--font-text);
border-radius: var(--radius);
box-shadow: var(--shadow);
}CSS variables are the foundation of most dark mode implementations: you redefine the same variables based on an attribute or a class on <html>.
:root {
--bg: #ffffff;
--text: #1e293b;
}
html.dark {
--bg: #0f172a;
--text: #f1f5f9;
}
body {
background-color: var(--bg);
color: var(--text);
transition: background-color 0.2s ease, color 0.2s ease;
}Rather than waiting for a click, you can apply dark mode automatically when the user has chosen it in their system, thanks to theprefers-color-scheme media query. Only the variable values change: no component needs to be modified.
:root {
--bg: #ffffff;
--text: #1e293b;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #0f172a;
--text: #f1f5f9;
}
}Since CSS variables are accessible from the browser, a script can read and change them on the fly: switch a theme color, adjust a size, react to the mouse position. The CSS doesn’t need to know anything about the script: it simply reads the new value.
const root = document.documentElement;
// Change a variable
root.style.setProperty("--color-primary", "#059669");
// Read a variable's current value
const value = getComputedStyle(root).getPropertyValue("--color-primary").trim();
console.log(value);Best practice
Group your most-used variables (main colors, spacing, border radii, shadows) in a single:root block at the top of your main CSS file — it becomes your centralized “design palette”.
A limitation to know about
A variable can’t be used to write a media query condition: @media (min-width: var(--bp))doesn’t work. However, nothing prevents you from redefining variables inside a media query, as in the dark mode example.
Exercise
:root block with 3-4 variables (a primary color, a text color, a spacing value), then use them in at least 3 different places on your page.Exercise: derived spacing
--space variable, then derive two other spacing values withcalc(). Change the base variable and watch the whole page adjust.Exercise: light and dark theme
prefers-color-scheme, then add a button that toggles the dark class with JavaScript.Going further
.success,.error,.info) that locally redefine the same color variable.