CSS Custom Properties & Theme Switching

CSS Custom Properties & Theme Switching in CSS: CSS Custom Properties (commonly called CSS Variables) allow values to be stored, reused, and inherited down the…

CSS Custom Properties (commonly called CSS Variables) allow values to be stored, reused, and inherited down the DOM tree. Unlike preprocessor variables (Sass/Less) which compile to static values at build time, CSS variables are live, reactive, and accessible via JavaScript.


Declaration & Scope Hierarchy

Variables are declared with two leading dashes (--name) and accessed with var(--name, fallback):

/* Global Scope (:root matches the <html> element) */
:root {
  --font-family-sans: 'Inter', system-ui, sans-serif;
  --color-primary: #2563eb;
  --color-success: #16a34a;
  --spacing-unit: 8px;
  --border-radius-md: 0.5rem;
}

/* Local Component Override */
.hero-banner {
  /* Re-assigning variable overrides it for all descendant children */
  --color-primary: #38bdf8;
  background-color: var(--color-primary);
}

Bulletproof Dark Mode Architecture

Modern theme switching combines the user's operating system preferences with manual toggle overrides:

/* 1. Light Theme Tokens (Default) */
:root {
  --bg-canvas: #ffffff;
  --bg-card: #f8fafc;
  --text-main: #0f172a;
  --border-subtle: #e2e8f0;
}

/* 2. OS Preference Match */
@media (prefers-color-scheme: dark) {
  :root:not([data-theme="light"]) {
    --bg-canvas: #090d16;
    --bg-card: #131b2e;
    --text-main: #f8fafc;
    --border-subtle: #1e293b;
  }
}

/* 3. Manual JavaScript Class/Attribute Toggle */
[data-theme="dark"] {
  --bg-canvas: #090d16;
  --bg-card: #131b2e;
  --text-main: #f8fafc;
  --border-subtle: #1e293b;
}

body {
  background-color: var(--bg-canvas);
  color: var(--text-main);
  transition: background-color 200ms ease, color 200ms ease;
}

Manipulating CSS Variables with JavaScript

// Read a computed CSS variable
const rootStyles = getComputedStyle(document.documentElement);
const brandColor = rootStyles.getPropertyValue('--color-primary').trim();

// Dynamically set a CSS variable at runtime (e.g., custom user branding)
document.documentElement.style.setProperty('--color-primary', '#8b5cf6');

Exercises

  1. Build a design token system containing primary, secondary, surface, and semantic text colors.
  2. Implement a JavaScript theme switcher that toggles data-theme="dark" and persists the selection in localStorage.
  3. Compare Sass variables ($primary) against native CSS variables (--primary) in terms of runtime reactivity.