---
title: "CSS – Custom Properties (Variables)"
url: https://www.khanwaseem.com/blog/css-tutorial/css-custom-properties-variables
author: "khan Waseem"
published: 2026-11-28
updated: 2026-11-29
topics: ["CSS Tutorial", "course"]
description: "Learn CSS custom properties (CSS variables): how to declare them, use var() with fallbacks, scope and override them in components, build light and dark themes, make layouts responsive, and read or change them from…"
---

# CSS – Custom Properties (Variables)

Table of Contents

[Toggle](#)

- [Introduction:](#introduction)
- [Part 1: The Basics](#part-1-the-basics)[1. Declaring a Custom Property:](#1-declaring-a-custom-property)
- [2. Using a Variable with var():](#2-using-a-variable-with-var)
- [3. Fallback Values:](#3-fallback-values)
- [4. Names Are Case-Sensitive:](#4-names-are-case-sensitive)

- [Part 2: Scope and Inheritance](#part-2-scope-and-inheritance)[5. Variables Follow the Cascade:](#5-variables-follow-the-cascade)
- [6. Overriding Variables for Variants:](#6-overriding-variables-for-variants)
- [7. Doing Maths with calc():](#7-doing-maths-with-calc)

- [Part 3: Real-World Uses](#part-3-real-world-uses)[8. Light and Dark Themes:](#8-light-and-dark-themes)
- [9. Responsive Layouts:](#9-responsive-layouts)
- [10. Reading and Changing Variables with JavaScript:](#10-reading-and-changing-variables-with-javascript)

- [Part 4: Advanced Details and Common Mistakes](#part-4-advanced-details-and-common-mistakes)[11. Invalid Values Do Not Fall Back to Earlier Rules:](#11-invalid-values-do-not-fall-back-to-earlier-rules)
- [12. Typed Variables with @property:](#12-typed-variables-with-property)
- [13. Where You Cannot Use var():](#13-where-you-cannot-use-var)
- [14. Naming and Organising Variables:](#14-naming-and-organising-variables)

- [Browser Support:](#browser-support)
- [Conclusion:](#conclusion)

## 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](https://blog.khanwaseem.com/css-color/), [CSS measurement units](https://blog.khanwaseem.com/css-measurement-units/) and [CSS @ rules](https://blog.khanwaseem.com/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`:

```css
:root {
  --brand: #1a1a1a;
  --radius: 8px;
}Code language: CSS (css)
```

A few things to notice:

- The name must start with `--`. After that you can use letters, numbers, dashes and underscores, such as `--brand`, `--space-2` or `--card_bg`.

- `:root` is 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:

```css
.btn {
  background-color: var(--brand);
  border-radius: var(--radius);
}

/* Computed in the browser:
   background-color: rgb(26, 26, 26)
   border-radius:    8px */Code language: CSS (css)
```

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:

```css
.notice {
  color: var(--missing, red);
}
/* --missing is not defined anywhere, so color: rgb(255, 0, 0) */Code language: CSS (css)
```

You can even nest fallbacks, so the browser tries one variable, then another, then a fixed value:

```css
.notice {
  color: var(--missing, var(--also-missing, blue));
}
/* Neither variable exists, so color: rgb(0, 0, 255) */Code language: CSS (css)
```

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:

```css
.title {
  --Main: red;
  --main: green;
  color: var(--main);
}
/* color: rgb(0, 128, 0), green, because --main and --Main are different */Code language: CSS (css)
```

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**:

```css
.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 */
}Code language: CSS (css)
```

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:

```css
.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) */Code language: CSS (css)
```

```xml
<button class="button">Save</button>
<button class="button ghost">Cancel</button>Code language: HTML, XML (xml)
```

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:

```css
:root {
  --space: 4;
}

.section {
  margin-top: calc(var(--space) * 4px);
}
/* margin-top: 16px */Code language: CSS (css)
```

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()`:

```css
.wrong {
  --gap: 10;
  margin-top: var(--gap)px;   /* does NOT work */
}
/* margin-top: 0px */Code language: CSS (css)
```

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:

```css
:root {
  --bg: #ffffff;
  --fg: #000000;
}

[data-theme="dark"] {
  --bg: #000000;
  --fg: #ffffff;
}

body {
  background-color: var(--bg);
  color: var(--fg);
}Code language: CSS (css)
```

```xml
<!-- Light (default) -->
<html>

<!-- Dark -->
<html data-theme="dark">Code language: HTML, XML (xml)
```

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:

```javascript
document.documentElement.dataset.theme = "dark";Code language: JavaScript (javascript)
```

You can also follow the user’s system setting automatically with a media query:

```css
@media (prefers-color-scheme: dark) {
  :root {
    --bg: #000000;
    --fg: #ffffff;
  }
}Code language: CSS (css)
```

### 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.

```css
.products {
  --cols: 1;
  display: grid;
  grid-template-columns: repeat(var(--cols), 1fr);
}

@media (min-width: 800px) {
  .products {
    --cols: 3;
  }
}Code language: CSS (css)
```

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:

```css
.box {
  --size: 10px;
  width: var(--size);
}Code language: CSS (css)
```

```javascript
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"Code language: JavaScript (javascript)
```

To read a global variable, read it from the `<html>` element:

```javascript
getComputedStyle(document.documentElement).getPropertyValue("--brand"); // "#1a1a1a"Code language: JavaScript (javascript)
```

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:

```css
.message {
  color: blue;
  --c: 20px;
  color: var(--c);   /* 20px is not a colour */
}
/* color: rgb(0, 0, 0), NOT blue */Code language: CSS (css)
```

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:

```css
@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) */Code language: CSS (css)
```

Registered properties have two big benefits:

- **Type safety:** an invalid value is rejected and the `initial-value` is used.

- **Animation:** the browser knows `--angle` is 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 as `800px`, 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:

```css
: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);
}Code language: CSS (css)
```

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 `:root` and component variables on the component’s own class.

- Prefix component variables with the component name, such as `--btn-bg` or `--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.

### Related posts:

[CSS – Pseudo Classes](https://blog.khanwaseem.com/css-pseudo-classes/)
[CSS – @ Rules](https://blog.khanwaseem.com/css-rules/)
[CSS – Links](https://blog.khanwaseem.com/css-links/)
[JavaScript and Cookies](https://blog.khanwaseem.com/javascript-and-cookies/)

Powered by [YARPP](https://yarpp.com).
