Every stylesheet of any size repeats itself. The same brand colour appears in the header, the buttons, the links, and the footer. The same spacing value shows up in card padding, section margins, and form gaps. When the design changes, someone has to find every one of those values and update them by hand, and one missed instance leaves the site looking inconsistent. CSS variables, formally called custom properties, solve that problem directly in the browser. You define a value once, give it a name, and refer to that name everywhere the value is needed. Change the definition in one place and every use updates with it.
This guide covers the full working pattern: defining variables, using them with the var function, setting fallbacks, scoping variables to components, building a light and dark theme, and using variables inside calculations. Variables pair naturally with layout work, so you will see them alongside ideas from our flexbox layout examples and the responsive media queries guide, where variables make breakpoint adjustments much cleaner.
Defining and Using a Variable
A custom property is any CSS property whose name starts with two dashes. You can define one on any selector, but the most common place is the root pseudo-class, which matches the html element and makes the variable available to the whole document. To use the variable, you pass its name to the var function wherever a normal value would go.
:root {
--brand: #2563eb;
--brand-dark: #1e40af;
--text: #1f2937;
--space: 1rem;
}
.button {
background: var(--brand);
color: #ffffff;
padding: var(--space);
}
.button:hover {
background: var(--brand-dark);
}
Take this example piece by piece. Inside the root block, four variables are declared. The brand variable holds the main blue, brand-dark holds a deeper shade for hover states, text holds the standard reading colour, and space holds a one rem spacing unit. None of these lines style anything visible yet; they simply store values under names. The button rule then uses var with the brand name as its background, white text, and the space variable as padding. The hover rule swaps the background to the darker variable. If the brand colour ever changes, you edit the single line in the root block and the button, its hover state, and every other element using that name all change together. That single edit point is the entire value of the technique.
Naming deserves a moment of care. Name variables after what they represent, not after the value they currently hold. A variable called brand or surface or danger will still make sense next year. A variable called blue or sixteen will mislead everyone the day the brand turns green or the spacing scale changes. Many teams use a two-part pattern, such as color-primary, color-surface, space-small, and space-large, which groups related tokens together and makes autocomplete in an editor genuinely useful.
Fallback Values
The var function accepts a second argument: a fallback value that the browser uses when the variable is not defined or is invalid. Fallbacks are a safety net. They matter most in reusable components, in stylesheets that load in pieces, and during refactors when a variable is renamed in one file before another.
.alert {
border: 1px solid var(--alert-border, #d1d5db);
background: var(--alert-bg, #f9fafb);
padding: var(--alert-padding, 0.75rem);
}
.alert-error {
--alert-border: #dc2626;
--alert-bg: #fef2f2;
}
Here the alert component reads three variables, and each var call carries a sensible default after the comma. A plain alert therefore renders with a light grey border, an off-white background, and comfortable padding even if nobody defines anything. The error variant does something elegant: instead of rewriting the border and background properties, it only redefines the variables themselves. Because the base rule reads the variables, changing the variables changes the result. This is the component theming pattern in miniature, and once you see it you will use it everywhere. A card, a badge, or a button can expose a handful of variables as its settings, and variants become two or three lines each instead of a full copy of the component styles.
One detail to remember: if the variable is defined but holds a value that does not fit the property, such as a colour used where a length is required, the declaration becomes invalid at computed time and the fallback does not rescue it. Fallbacks protect against missing variables, not against wrong types. Keeping names clear about what kind of value they hold, like space or color in the name, prevents that class of bug.
Scoping: Global, Section, and Component Variables
Variables follow the cascade and inheritance, just like normal properties. A variable defined on root is global. A variable defined on a specific element applies to that element and its children, and it overrides a global variable of the same name within that subtree. This scoping behaviour turns variables into a layout tool, not just a colour store.
.section {
--section-bg: #ffffff;
background: var(--section-bg);
padding: 3rem 1rem;
}
.section-alt {
--section-bg: #f3f4f6;
}
.card {
--card-radius: 8px;
border-radius: var(--card-radius);
}
.card-round {
--card-radius: 20px;
}
In this snippet, every section uses its section background variable for its background, defaulting to white through the section rule itself. Adding the alt class to a section changes only the variable, and the background follows. The card example does the same for corner radius: the normal card reads eight pixels from its own scoped variable, and the round variant redefines that variable to twenty pixels. Notice that child elements inside the card would also inherit the card radius variable, so an inner element could use the same variable for a matching inner corner. Scoping like this keeps related values consistent inside a component while leaving the rest of the page untouched. It is also how a single page can host two differently themed areas without any duplicated rules, an idea that works well with the section patterns in our centring methods guide when a hero and a content section need different treatments.
Building a Dark Theme
The most popular use of variables is theming, and the clearest example is a dark mode. The pattern is simple: define semantic colour variables such as background, surface, and text on root for the light theme, then redefine the same variables under a dark condition. Every component that uses the semantic names switches automatically, with no extra rules per component.
:root {
--bg: #ffffff;
--surface: #f9fafb;
--text: #111827;
--muted: #6b7280;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #111827;
--surface: #1f2937;
--text: #f9fafb;
--muted: #9ca3af;
}
}
body {
background: var(--bg);
color: var(--text);
}
.panel {
background: var(--surface);
color: var(--text);
}
Follow the flow. The first root block sets light values: white page background, pale panel surface, near-black text, and a grey for secondary text. The media query block listens for the operating system dark preference and, when it matches, redefines the same four names with dark values. The body and panel rules never change; they simply read the variables, so they repaint in whichever theme is active. This is why semantic naming matters so much. If the variable were called white, the dark theme would need a variable named white that holds a dark colour, which confuses everyone. Called background, it stays honest in both themes. The media query side of this pattern is explained further in the media queries guide, since prefers-color-scheme is a media feature just like width.
You can also drive the theme with a class or a data attribute on the html element instead of, or alongside, the system preference. A manual toggle typically sets a data-theme attribute with JavaScript, and a selector matching that attribute redefines the variables. The CSS half is identical in spirit: one more block that reassigns the same names. Storing the visitor choice so it persists between pages is a small storage job, covered in our notes on JavaScript local storage if you build that toggle.
Variables in Calculations and Responsive Design
Variables hold raw values, and those values can feed the calc function to build derived sizes. This is where a spacing scale becomes powerful: define one base unit and let components multiply it, instead of hard-coding a dozen unrelated padding values across the file.
:root {
--unit: 0.5rem;
--gap: calc(var(--unit) * 3);
}
.toolbar {
display: flex;
gap: var(--gap);
padding: calc(var(--unit) * 2);
}
@media (min-width: 768px) {
:root {
--unit: 0.625rem;
}
}
Here the unit variable is half a rem. The gap variable is calculated as three units, which works out to one and a half rem, and it is itself used as a normal variable by the toolbar. The toolbar is a flex row with that gap and padding of two units. Then comes the responsive trick: at viewports of 768 pixels and wider, only the unit variable grows slightly. Every padding, gap, and margin derived from it grows in proportion, across the whole site, from a three-line change. Without variables that same adjustment would mean hunting through the stylesheet for every spacing value and deciding one by one whether it should scale. With a token system, the decision was made once, when the values were defined in terms of the unit.
The same idea applies to typography. A base font size variable can drive heading sizes through calc multiplications, keeping the type scale in ratio at every breakpoint. Just keep the chain shallow. A variable that depends on a variable that depends on a third variable is legal CSS, but it makes debugging slow, because the final value is no longer visible in any single place. One level of derivation is a good working limit for most teams.
Variables and JavaScript
Unlike preprocessor variables, which disappear at build time, CSS custom properties are live in the browser. JavaScript can read them and change them at runtime, and the page updates instantly. This opens up small interactive features, such as a user-controlled accent colour or a slider that adjusts spacing or image size, with almost no code.
/* CSS */
:root {
--accent: #2563eb;
}
.link {
color: var(--accent);
}
// JavaScript: read and change the variable
const root = document.documentElement;
const current = getComputedStyle(root)
.getPropertyValue('--accent');
root.style.setProperty('--accent', '#059669');
The CSS half defines an accent variable on root and uses it for link colour. The JavaScript half first grabs the html element, which is what documentElement refers to. It then reads the computed value of the accent property, which is useful when you need to know the current setting, and finally sets the property to a green value on that element. The moment the setProperty line runs, every element using the accent variable repaints, with no class changes and no style recalculation code of your own. Setting the variable on a narrower element instead of root scopes the change to that subtree, which is handy for previewing a theme on one panel before applying it everywhere.
Common Mistakes to Avoid
A few pitfalls show up repeatedly. The first is forgetting that variable names are case sensitive. A variable defined as brand-Color and read as brand-color are two different variables, and the read will quietly fall back or fail. Pick one casing convention, usually lowercase with dashes, and stick to it. The second is defining a variable inside a rule and expecting it to exist elsewhere. A variable defined on a button class exists only for elements matching that class and their children; reading it on the header will not find it. When in doubt, global tokens belong on root.
The third pitfall is storing a full shorthand in one variable when you actually need the parts separately. A variable holding a complete border value like 1px solid red works in a border property, but you cannot later change just its colour. Prefer one variable per value: width, style, and colour as separate tokens when there is any chance they will vary independently. The fourth is over-tokenising. Not every value needs a variable. A one-off width used in exactly one place gains nothing from a name, and a root block with two hundred tokens is as hard to maintain as the repetition it replaced. Tokenise what repeats, what themes, and what scales. Leave the rest as plain values.
Finally, remember the media query limitation mentioned in the responsive guide: variables cannot be used inside a media query condition in plain CSS. You cannot write a query that reads a breakpoint variable. What you can do, as the calc example showed, is redefine variables inside a query, which covers most of the practical need.
Conclusion
CSS variables turn a stylesheet from a pile of repeated values into a small set of named decisions. Define global tokens on root with semantic names, give components their own scoped variables and fallbacks, and let themes and responsive steps work by redefining those names rather than rewriting rules. Add calc for derived spacing and type, and JavaScript access when a setting should change at runtime. Start with colours and spacing, the two places repetition hurts most, and the rest of the system tends to grow naturally from there.
Tagged: css snippets css theming css variables custom properties dark mode css root variables


