CSS – Custom Properties (Variables)

Introduction:
Imagine your website uses the same dark grey, #1a1a1a, in forty places: buttons, headings, borders and the footer. One day you decide it should be a little lighter. Without variables you have to find and replace forty values and hope you did not miss one, or change one that only looked the same by accident.
CSS custom properties, usually called CSS variables, fix this. You give a value a name once, and then use that name everywhere. Change the value in one place and the whole page updates.
But custom properties are much more than “find and replace” for colours. Unlike variables in Sass or Less, they live in the browser, follow the normal CSS cascade and inheritance, can change inside a media query, and can be read and changed with JavaScript while the page is running. That makes them the foundation of modern theming, dark mode and design systems.
In this lesson we will learn how to declare and use them, how fallbacks and scoping work, how to build themes and responsive layouts with them, and the common mistakes to avoid. It builds on the earlier lessons on CSS colors, CSS measurement units and CSS @ rules.
Every example below was tested in Chromium, and the comments show the real computed values the browser returned.
Part 1: The Basics
1. Declaring a Custom Property:
A custom property is any property whose name starts with two dashes (--). You declare it inside a rule, just like color or margin:
:root {
--brand: #1a1a1a;
--radius: 8px;
}
A few things to notice:
- The name must start with
--. After that you can use letters, numbers, dashes and underscores, such as--brand,--space-2or--card_bg. :rootis a selector that matches the<html>element. Declaring variables there makes them available to every element on the page, because custom properties are inherited.- The value can be almost anything: a colour, a length, a number, a whole shadow, even a list of fonts.
Declaring a custom property does nothing visible by itself. It just stores a value that other properties can use.
2. Using a Variable with var():
To use the value, call the var() function with the variable’s name:
.btn {
background-color: var(--brand);
border-radius: var(--radius);
}
/* Computed in the browser:
background-color: rgb(26, 26, 26)
border-radius: 8px */
Now every button uses the brand colour. If you change --brand in :root, every button changes with it, along with every other rule that uses var(--brand).
3. Fallback Values:
What happens if the variable does not exist? var() accepts a second argument, the fallback, which is used when the variable is not defined:
.notice {
color: var(--missing, red);
}
/* --missing is not defined anywhere, so color: rgb(255, 0, 0) */
You can even nest fallbacks, so the browser tries one variable, then another, then a fixed value:
.notice {
color: var(--missing, var(--also-missing, blue));
}
/* Neither variable exists, so color: rgb(0, 0, 255) */
Fallbacks are very useful in reusable components: the component works with sensible defaults, and a page can customise it by defining the variable.
4. Names Are Case-Sensitive:
Normal CSS properties are not case-sensitive (COLOR works the same as color), but custom property names are. --main and --Main are two different variables:
.title {
--Main: red;
--main: green;
color: var(--main);
}
/* color: rgb(0, 128, 0), green, because --main and --Main are different */
To avoid confusion, pick one style and stick with it. Most teams use lowercase names with dashes, like --text-muted.
Part 2: Scope and Inheritance
5. Variables Follow the Cascade:
Custom properties are inherited: when you set one on an element, all of its children can see it. When you set one on a smaller element instead of :root, only that element and its children can see it. This is called scoping:
.card {
--pad: 24px;
}
.card .inner {
padding: var(--pad, 0px); /* 24px: it is inside .card */
}
.outside {
padding: var(--pad, 0px); /* 0px: --pad is not visible here, so the fallback is used */
}
This is the biggest difference from Sass variables. A Sass variable is replaced with its value when the CSS is compiled, so it knows nothing about the HTML structure. A CSS custom property is resolved by the browser, per element, depending on where that element sits in the page.
6. Overriding Variables for Variants:
Scoping makes component variants very clean. Instead of rewriting every property for each variant, the base class uses variables and each variant only changes the variables:
.button {
--btn-bg: black;
--btn-fg: white;
background-color: var(--btn-bg);
color: var(--btn-fg);
}
.button.ghost {
--btn-bg: transparent;
--btn-fg: black;
}
/* .button -> background rgb(0, 0, 0), color rgb(255, 255, 255)
.button.ghost -> background rgba(0, 0, 0, 0), color rgb(0, 0, 0) */
<button class="button">Save</button>
<button class="button ghost">Cancel</button>
The ghost button never repeats background-color or color. It only changes the inputs. If you later add a border that uses var(--btn-fg), every variant gets the right border colour automatically.
7. Doing Maths with calc():
Variables work inside calc(), which lets you build a spacing scale from one base number:
:root {
--space: 4;
}
.section {
margin-top: calc(var(--space) * 4px);
}
/* margin-top: 16px */
Multiplying by 4px is how you turn a plain number into a length. This is the correct way to add a unit. A very common mistake is to write the unit straight after the var():
.wrong {
--gap: 10;
margin-top: var(--gap)px; /* does NOT work */
}
/* margin-top: 0px */
The browser does not glue 10 and px together into 10px. It sees two separate pieces, 10 and px, which is not a valid length, so the declaration fails. Always use calc(var(--gap) * 1px), or store the unit in the variable itself (--gap: 10px).
Part 3: Real-World Uses
8. Light and Dark Themes:
Theming is where custom properties really shine. Define the colours once for the light theme, then override only the variables for the dark theme. The rest of the CSS never changes:
:root {
--bg: #ffffff;
--fg: #000000;
}
[data-theme="dark"] {
--bg: #000000;
--fg: #ffffff;
}
body {
background-color: var(--bg);
color: var(--fg);
}
<!-- Light (default) -->
<html>
<!-- Dark -->
<html data-theme="dark">
In our test, an element inside [data-theme="dark"] computed to background-color: rgb(0, 0, 0) and color: rgb(255, 255, 255), while an element outside it stayed white with black text.
To switch themes with a button, JavaScript only needs to change one attribute:
document.documentElement.dataset.theme = "dark";
You can also follow the user’s system setting automatically with a media query:
@media (prefers-color-scheme: dark) {
:root {
--bg: #000000;
--fg: #ffffff;
}
}
9. Responsive Layouts:
Because variables are resolved by the browser, you can change their value inside a media query. Sass variables cannot do this, because they no longer exist once the CSS is compiled.
.products {
--cols: 1;
display: grid;
grid-template-columns: repeat(var(--cols), 1fr);
}
@media (min-width: 800px) {
.products {
--cols: 3;
}
}
In our test the grid had one column (384px) at a 400px wide screen and three columns (328px 328px 328px) at 1000px. The layout rule is written once, and the media query only changes one number.
10. Reading and Changing Variables with JavaScript:
JavaScript can read a variable with getPropertyValue() and change it with setProperty(). Every rule that uses the variable updates instantly:
.box {
--size: 10px;
width: var(--size);
}
const box = document.querySelector(".box");
// Read the value
getComputedStyle(box).getPropertyValue("--size"); // "10px"
getComputedStyle(box).width; // "10px"
// Change it
box.style.setProperty("--size", "120px");
getComputedStyle(box).width; // "120px"
To read a global variable, read it from the <html> element:
getComputedStyle(document.documentElement).getPropertyValue("--brand"); // "#1a1a1a"
This is a clean way to connect JavaScript and CSS. For example, a scroll handler can set --scroll and CSS can use it in a transform, or a colour picker can set --brand and recolour the whole site. JavaScript only sets values, and CSS still decides how things look.
Part 4: Advanced Details and Common Mistakes
11. Invalid Values Do Not Fall Back to Earlier Rules:
This one surprises many developers. Normally, if you write an invalid value, the browser ignores that line and keeps the previous one. With variables, it works differently:
.message {
color: blue;
--c: 20px;
color: var(--c); /* 20px is not a colour */
}
/* color: rgb(0, 0, 0), NOT blue */
The browser cannot know whether var(--c) is valid until it works out the value, and by then it has already thrown away color: blue. So the property becomes invalid at computed-value time and behaves as if you wrote unset. Because color is an inherited property, it takes the parent’s colour (black here), not blue.
The lesson: do not rely on an earlier declaration as a safety net for a variable. Use the var() fallback instead, and keep each variable to one kind of value.
12. Typed Variables with @property:
By default, the browser treats a custom property’s value as plain text and does not check its type. The @property rule lets you register a variable with a type, an initial value, and whether it inherits:
@property --angle {
syntax: "<angle>";
inherits: false;
initial-value: 0deg;
}
.ok { --angle: 45deg; } /* --angle: 45deg */
.bad { --angle: red; } /* red is not an angle, so --angle: 0deg (initial-value) */
Registered properties have two big benefits:
- Type safety: an invalid value is rejected and the
initial-valueis used. - Animation: the browser knows
--angleis an angle, so it can transition and animate it smoothly. An unregistered variable just jumps from one value to the other, because the browser does not know how to blend two pieces of text.
For example, a rotating gradient border becomes possible by animating --angle inside a conic-gradient().
13. Where You Cannot Use var():
Variables can only be used inside property values. They do not work in these places:
- Property names:
var(--side): 10px;is invalid. You cannot build a property name from a variable. - Selectors:
.var(--name) { }does not work. - Media query conditions:
@media (min-width: var(--bp))does not work, because media queries are evaluated before any element exists. Use a fixed value such as800px, and change variables *inside* the query instead (as in example 9).
14. Naming and Organising Variables:
Once a project has dozens of variables, good names matter more than the values. A simple approach that scales well uses two layers:
:root {
/* 1. Raw values (the palette) */
--gray-900: #1a1a1a;
--gray-100: #f2f2f2;
/* 2. Meaning (what the colour is for) */
--color-text: var(--gray-900);
--color-surface: var(--gray-100);
}
Components use only the meaning variables (--color-text), never the raw ones. To change the theme, you point the meaning variables at different raw values, and no component CSS needs to change. This is how most design systems, including the variables produced by tools like Tailwind CSS v4, are organised.
A few more tips:
- Put global variables in
:rootand component variables on the component’s own class. - Prefix component variables with the component name, such as
--btn-bgor--card-pad, so they don’t clash. - Add a fallback to
var()in shared components that might be used on pages without your variables.
Browser Support:
Custom properties work in every modern browser (Chrome, Edge, Firefox and Safari) and have done so for many years, so you can use them in production today. @property is also supported in all current versions of these browsers. Internet Explorer never supported custom properties, but it is no longer maintained.
Conclusion:
CSS custom properties let you name a value once and use it everywhere. We learned how to declare them with --name, use them with var(), and protect them with fallbacks. Because they follow the cascade, you can scope them to a component, override them for variants, change them inside media queries, and switch whole themes by changing a few values. JavaScript can read and set them, and @property adds types and smooth animation.
We also covered the traps: names are case-sensitive, var(--x)px does not add a unit, invalid values do not fall back to earlier rules, and var() cannot be used in property names, selectors or media query conditions.
In the next lesson we will learn CSS container queries, which let a component change its layout based on the size of its own container instead of the whole screen.


