Tutorials CSS Custom Properties
Ch 48 / 60
Chapter 48 Intermediate 10 min read CSS

CSS Custom Properties (Variables)

CSS custom properties — declared with -- and used with var() — are one of the most powerful features in modern CSS. Unlike preprocessor variables (Sass, Less) which compile away at build time, CSS custom properties live in the browser, participate in the cascade and inheritance, can be overridden in any selector scope, and can be read and written by JavaScript at runtime. This makes them the foundation of design token systems, component theming, dark mode switching, and dynamic UI.

What you'll learn
Declaring custom properties with --
Using var() with fallback values
Scope, inheritance and the cascade
Design token system on :root
Dark mode with custom properties
JavaScript read/write at runtime

Declaring and Using Custom Properties

Custom properties start with -- (two hyphens). They are case-sensitive. The var() function reads them and accepts an optional fallback:

--primary-color: #264de4;
--
required prefix
property name
your custom name (case-sensitive)
value
any valid CSS value
color: var(--primary-color, #0070f3);
property
where you use the value
var()
reads the custom property
--primary-color
the custom property to read
fallback value
used if property is undefined
CSS — declaring and using custom properties
/* ── Declaring on :root — globally available ── */
:root {
  --color-primary:    #264de4;
  --color-text:       #0f172a;
  --space-md:         1rem;
  --radius-card:      12px;
  --font-mono:        'JetBrains Mono', monospace;
}

/* ── Using with var() ── */
.btn    { background:    var(--color-primary); }
.card   { border-radius: var(--radius-card); }
.hero   { padding:       var(--space-md); }

/* ── Fallback value — used if property is undefined ── */
.el     { color:  var(--color-accent, #f97316); }
.el     { color:  var(--undefined, var(--color-primary, blue)); } /* nested fallback */

/* ── Custom properties accept any valid CSS value ── */
:root {
  --shadow:     0 4px 16px rgba(0,0,0,.1);
  --gradient:   linear-gradient(135deg,#264de4,#a855f7);
  --transition: .3s cubic-bezier(.34,1.56,.64,1);
  --ratio:      16/9;          /* can store partial values */
}
.card {
  box-shadow:    var(--shadow);
  background:    var(--gradient);
  transition:    transform var(--transition);
  aspect-ratio:  var(--ratio);
}

Scope, Inheritance & the Cascade

Custom properties follow the same cascade and inheritance rules as regular CSS. A property declared on an element is available to that element and all its descendants. Inner scopes override outer ones:

:root { --color: blue; } ← available everywhere
.section { --color: green; } ← overrides inside .section
.card { color: var(--color); } ← gets green (inherits from .section)
.card .badge { color: var(--color); } ← also gets green
.other { color: var(--color); } ← gets blue (inherits from :root)
Local scope — same component, different variables per instance

All 4 buttons use the same .scope-btn class. Each variant only overrides --btn-bg, --btn-color and --btn-radius.

CSS — scope, inheritance and component theming
/* ── Global scope on :root ── */
:root  { --color: blue; }

/* ── Local override — only affects descendants ── */
.dark-section { --color: lightblue; }

/* ── Component local variables ── */
.btn {
  --btn-bg:     #264de4;   /* default values on component */
  --btn-color:  #fff;
  --btn-radius: 8px;

  background:   var(--btn-bg);
  color:        var(--btn-color);
  border-radius:var(--btn-radius);
}

/* Variants — only override what changes */
.btn-danger  { --btn-bg: #ef4444; }
.btn-success { --btn-bg: #22c55e; }
.btn-pill    { --btn-radius: 999px; --btn-bg: rgba(38,77,228,.12); --btn-color: #264de4; }
.btn-lg      { --btn-radius: 12px; }

/* ── Inline style override (per element) ── */
<button style="--btn-bg:#f59e0b">Custom</button>

/* ── Properties do NOT inherit by default
   Use inherit explicitly when needed ── */
.child { color: var(--parent-color); }  /* works — custom props DO inherit */

Design Token System

The best practice is to declare all your design values — colours, spacing, type, shadows, radii — as custom properties on :root. This creates a single source of truth that every component references:

--color-primary
#264de4
--color-success
#22c55e
--color-danger
#ef4444
--color-surface
#f8fafc
--space-md
clamp(1rem, 2vw, 2rem)
--radius-card
12px
--shadow-md
0 4px 16px …
--transition
.3s ease-out
CSS — complete design token system
:root {
  /* ── Colours ── */
  --color-primary:    #264de4;
  --color-primary-lt: rgba(38,77,228,.12);
  --color-success:    #22c55e;
  --color-danger:     #ef4444;
  --color-warning:    #f97316;
  --color-text:       #0f172a;
  --color-text-2:     #64748b;
  --color-bg:         #ffffff;
  --color-surface:    #f8fafc;
  --color-border:     #e2e8f0;

  /* ── Typography ── */
  --font-sans:        system-ui, -apple-system, sans-serif;
  --font-mono:        'JetBrains Mono', monospace;
  --text-xs:          clamp(.75rem, 1vw, .875rem);
  --text-sm:          clamp(.875rem, 1.25vw, 1rem);
  --text-base:        clamp(1rem, 1.5vw, 1.125rem);
  --text-lg:          clamp(1.25rem, 2.5vw, 2rem);
  --text-xl:          clamp(1.875rem, 4vw, 3.75rem);

  /* ── Spacing ── */
  --space-xs:  clamp(.25rem, .5vw, .5rem);
  --space-sm:  clamp(.5rem,  1vw,  1rem);
  --space-md:  clamp(1rem,   2vw,  2rem);
  --space-lg:  clamp(1.5rem, 3vw,  3rem);
  --space-xl:  clamp(2.5rem, 5vw,  5rem);

  /* ── Shapes & effects ── */
  --radius-sm:    6px;
  --radius-md:    10px;
  --radius-lg:    16px;
  --radius-full:  999px;
  --shadow-sm:    0 1px 3px rgba(0,0,0,.08);
  --shadow-md:    0 1px 3px rgba(0,0,0,.08), 0 4px 16px rgba(0,0,0,.10);
  --shadow-lg:    0 4px 8px rgba(0,0,0,.08), 0 16px 36px rgba(0,0,0,.14);
  --transition:   .25s ease-out;
  --transition-spring: .3s cubic-bezier(.34,1.56,.64,1);
}

/* ── Using tokens ── */
body    { font-family: var(--font-sans); color: var(--color-text); background: var(--color-bg); }
.btn    { background: var(--color-primary); border-radius: var(--radius-md); transition: var(--transition); }
.card   { box-shadow: var(--shadow-md); border-radius: var(--radius-lg); padding: var(--space-md); }

Dark Mode with Custom Properties

Custom properties make dark mode trivial: define light values on :root, override them in a dark-mode block. Every component automatically gets the new values — no extra rules needed. Click the theme buttons below to see it live:

CSS Custom Properties
Theme switches by only changing -- variables
New
Design Token System
Single source of truth for all values
Popular
CSS — dark mode and theme switching
/* ── Light mode (default) ── */
:root {
  --color-bg:      #ffffff;
  --color-surface: #f8fafc;
  --color-border:  #e2e8f0;
  --color-text:    #0f172a;
  --color-text-2:  #64748b;
  --shadow:        0 1px 3px rgba(0,0,0,.08), 0 4px 16px rgba(0,0,0,.10);
}

/* ── Dark mode — system preference ── */
@media (prefers-color-scheme: dark) {
  :root {
    --color-bg:      #0f172a;
    --color-surface: #1e293b;
    --color-border:  #334155;
    --color-text:    #f1f5f9;
    --color-text-2:  #94a3b8;
    --shadow:        0 1px 3px rgba(0,0,0,.3), 0 4px 16px rgba(0,0,0,.4);
  }
}

/* ── Manual toggle with data attribute ── */
[data-theme="dark"] {
  --color-bg:      #0f172a;
  --color-surface: #1e293b;
  --color-text:    #f1f5f9;
  /* other dark values... */
}

/* ── Colour-scheme theming — only override accent colour ── */
.theme-blue  { --color-primary: #264de4; }
.theme-green { --color-primary: #16a34a; }
.theme-purple{ --color-primary: #7c3aed; }

/* All components using var(--color-primary) update automatically */
body     { background: var(--color-bg);  color: var(--color-text); }
.card    { background: var(--color-surface); border-color: var(--color-border); }
.btn     { background: var(--color-primary); }

JavaScript Integration

CSS custom properties bridge CSS and JavaScript. You can read their current value and set new values at runtime — enabling dynamic theming, user preferences, and data-driven styling:

JavaScript — reading and writing custom properties
// ── Read a custom property ──
const root  = document.documentElement;
const value = getComputedStyle(root).getPropertyValue('--color-primary');
// value = ' #264de4' (may have leading space — use .trim())

// ── Set / override a custom property ──
root.style.setProperty('--color-primary', '#7c3aed');  // all components update instantly

// ── Remove (revert to stylesheet value) ──
root.style.removeProperty('--color-primary');

// ── Dark mode toggle (JS + data attribute) ──
function toggleDarkMode() {
  const html = document.documentElement;
  html.dataset.theme = html.dataset.theme === 'dark' ? 'light' : 'dark';
}

// ── Persist preference in localStorage ──
function setTheme(theme) {
  document.documentElement.dataset.theme = theme;
  localStorage.setItem('theme', theme);
}

// On load — restore saved preference
const saved = localStorage.getItem('theme');
if (saved) document.documentElement.dataset.theme = saved;

// ── Dynamic data-driven styling ──
// CSS: .bar { width: var(--progress); background: var(--color-primary); }
const bar = document.querySelector('.bar');
bar.style.setProperty('--progress', '73%');  // bar fills to 73%

// ── On an element (local scope) ──
const card = document.querySelector('.card');
card.style.setProperty('--btn-bg', userPick);  // only this card's button changes

CSS Custom Properties vs Sass/Less Variables

Feature CSS Custom Properties Sass/Less Variables
Lives in browser ✓ Yes — dynamic ✗ Compiled away at build time
Runtime changes ✓ JavaScript can read/write ✗ Cannot change after compile
Cascade & scope ✓ Participates fully ✗ Flat — no scope
Inheritance ✓ Inherited by children ✗ No inheritance concept
Media query override ✓ Can change at breakpoints ✗ No — values are fixed
Fallback values ✓ var(--x, fallback) ✗ No equivalent
Build step required ✓ None — native CSS ✗ Requires compiler
Functions / math Limited (use calc()) Richer — @functions, @each
Browser support All modern browsers Unlimited (compiles to CSS)
Free Resource
CSS3 Cheat Sheet — Custom Properties & Design Tokens
Complete reference covering CSS custom properties, var(), design token systems and dark mode patterns.
Download PDF

Try It Yourself

A complete design token system with theme switching — edit the :root variables to see all components update instantly:

Live Editor
✎ Editor
👁 Preview
Featured Course — Enroll Now
Modern Web Development With AI
Master HTML, CSS, JavaScript, React and Node.js with real projects and placement support.
120+
Chapters
40 hrs
Content
10 Real
Projects
4.9 ⭐
Rating
HTML5CSS3JavaScriptReact.jsNode.jsTailwind CSSAI Tools

Quick Check — Chapter 48

Questions & Answers
The fundamental difference is when they exist:

Sass variables are processed at build time by the Sass compiler. They get replaced with their values in the compiled CSS output — they never reach the browser as variables. Once compiled, the values are fixed and cannot change. They have no concept of scope, cascade, or inheritance.

CSS custom properties are native browser features that exist at runtime. They:
— Live in the browser and participate in the CSS cascade
— Can be overridden in any selector scope (inherited by children)
— Can be changed by JavaScript at runtime: el.style.setProperty('--x', 'value')
— Can be overridden by media queries: @media (prefers-color-scheme: dark) { :root { --bg: #000 } }
— Can accept any value including complex ones like gradients and box-shadow strings

In practice: Sass is still useful for its functions, mixins and control flow. CSS custom properties are preferred for anything dynamic — theming, dark mode, component customisation, JavaScript-driven UI.
Custom properties follow the same rules as all CSS — they cascade and are inherited. An element can read any custom property defined on itself or any ancestor:

:root { --color: blue; } — available to every element
.section { --color: green; } — overrides for .section and its children
.section .card { color: var(--color); } — reads green (inherited from .section)
.other { color: var(--color); } — reads blue (inherits from :root)

This enables powerful component theming:
.btn { --btn-bg: blue; background: var(--btn-bg); }
.btn-danger { --btn-bg: red; }

The same technique works with inline styles on individual elements, overriding for just that instance without a new class.
var(--property, fallback) — the fallback is used when the custom property is undefined or invalid in the current scope.

color: var(--color-accent, #f97316);
— If --color-accent is defined: uses it
— If it is not defined: uses #f97316

Fallbacks can be nested:
color: var(--color-accent, var(--color-primary, blue));
— Tries --color-accent first, then --color-primary, then the literal blue

Fallbacks are powerful for optional theming:
.card { background: var(--card-bg, var(--color-surface)); }
— If a parent sets --card-bg, it uses that
— Otherwise falls back to the global --color-surface token

Note: a property set to an empty value (--x: ;) is defined but invalid — the fallback is still not used in this case; instead, the inherited or initial value for the property is used.
There are two approaches:

1. System preference (automatic):
:root { --bg: #fff; --text: #0f172a; }
@media (prefers-color-scheme: dark) { :root { --bg: #0f172a; --text: #f1f5f9; } }

2. Manual toggle (user-controlled):
:root { --bg: #fff; }
[data-theme="dark"] { --bg: #0f172a; }
Then toggle with JavaScript: document.documentElement.dataset.theme = 'dark'

Once the token values are overridden, every component using var(--bg), var(--text) etc. automatically updates — no additional CSS rules needed. This is why the design token approach is so powerful: you write component styles once and theming is free.

Persist the preference: localStorage.setItem('theme', 'dark') and restore on page load before the first paint.
Reading a custom property:
const value = getComputedStyle(element).getPropertyValue('--color-primary').trim();
— Use getComputedStyle() to get the resolved value (including inherited ones)
— .trim() because the value often has a leading space

Writing / setting a custom property:
element.style.setProperty('--color-primary', '#7c3aed');
— Sets as an inline style on that element — overrides the stylesheet value for this element and its descendants
— To affect the whole page: use document.documentElement (the html element)

Removing (revert to stylesheet):
element.style.removeProperty('--color-primary');

Practical pattern — data-driven progress bar:
CSS: .bar { width: var(--progress, 0%); }
JS: bar.style.setProperty('--progress', '73%');
The bar instantly updates to 73% wide without touching any CSS rule.
Multiple Choice Questions
Question 1 of 5
Which declaration correctly defines a CSS custom property?
Question 2 of 5
What does color: var(--accent, #f97316) do when --accent is not defined?
Question 3 of 5
A custom property is defined on :root and overridden on .card. Which value does a <p> inside .card inherit?
Question 4 of 5
Which JavaScript correctly sets a custom property on the entire page?
Question 5 of 5
Which approach correctly implements dark mode using CSS custom properties and a manual toggle?
Chapter Summary
  • Declaration: --property-name: value — any name starting with --. Case-sensitive. Can hold any valid CSS value including complex ones like gradients and shadow strings.
  • Usage: var(--property-name) or with fallback: var(--x, fallback). Fallbacks can nest: var(--x, var(--y, blue)).
  • :root scope: declare globally available tokens on :root (the html element). All elements in the document inherit them.
  • Local scope: declare on any selector to override only within that subtree. Component theming: .btn { --btn-bg: blue } — variants override the one variable, all other styles are inherited from the base component.
  • Cascade and inheritance: custom properties follow the same rules as regular CSS. The nearest ancestor's definition wins. Children inherit from parents.
  • Design token system: store all design values (colours, spacing, typography, shadows, radii) on :root. Single source of truth — change once, updates everywhere.
  • Dark mode: override tokens in @media (prefers-color-scheme: dark) or [data-theme="dark"]. All components using var() update automatically.
  • JavaScript: read with getComputedStyle(el).getPropertyValue('--x').trim(). Set with el.style.setProperty('--x', value). Remove with el.style.removeProperty('--x').
  • vs Sass variables: CSS custom properties are live (runtime), scoped, cascading, JavaScript-accessible. Sass variables compile away and are static. Both serve different purposes.
~10 min read
Intermediate level
Chapter 48 of 60

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel