Skip to content

CSS Tutorial CSS Variables

CSS Variables (Custom Properties)

Lesson 153 of 182 2 min read By Deepak Paswan Updated Oct 4, 2026

Imagine your brand color appears in 40 places. If it changes, you have 40 edits to make. A CSS variable (officially, a custom property) stores the value in one place.

Creating one

A variable name starts with two dashes. You set it like any other property.

style.css
CSS
:root {
  --brand: #d94a00;
  --space: 16px;
}

Using one

Read it with var().

index.html
HTML
<style>
  :root { --brand: #d94a00; --space: 16px; }
  .btn   { background: var(--brand); color: #fff; padding: var(--space); border: 0; border-radius: 6px; }
  .title { color: var(--brand); }
  .card  { border: 2px solid var(--brand); padding: var(--space); margin-top: var(--space); }
</style>
<h2 class="title">Spring sale</h2>
<button class="btn">Shop now</button>
<div class="card">The same orange and the same spacing, from two variables.</div>

Change --brand to #1a5276 and press Run. Every use updates at once.

Fallback values

var(--name, fallback) uses the fallback when the variable is not defined:

style.css
JS
.note { color: var(--note-color, #333); }

Variables vs. Sass variables

If you have used a preprocessor like Sass, the difference is that CSS variables are alive in the browser. They follow the cascade, can be changed by JavaScript, and can be different in different parts of the page. That makes theming and dark mode possible. You will see both in the next lessons.

What variables can hold

Any CSS value, or part of a value: colors, lengths, font stacks, even shadows.

style.css
CSS
:root {
  --font-body: system-ui, sans-serif;
  --shadow: 0 4px 12px rgba(0,0,0,.15);
  --radius: 8px;
}
warning
Variables are case-sensitive
--Brand and --brand are different. And var(--brand) with a name that does not exist makes the whole declaration invalid at computed time, so the property falls back to its default or inherited value. Use a fallback in var() for safety.