← Back to Chapters

CSS Variables

? CSS Variables

⚡ Quick Overview

CSS Variables (also called custom properties) let you store reusable values in CSS. They improve readability, reusability, and theming by keeping key values (colors, font sizes, spacing) in one place. They are declared using --variable-name and accessed using var(--variable-name).

Example use cases:

  • Global theme colors (primary, background, text, border)
  • Consistent spacing and font sizes across the site
  • Easy light/dark theme switching

? Key Concepts

  • Custom property name: Always starts with --, e.g. --main-bg.
  • Defined on an element: Usually on :root for global access.
  • Accessed with var(): var(--main-bg) returns the variable’s value.
  • Scoped & inherited: Variables follow normal CSS inheritance rules.
  • Dynamic: Can be changed at runtime using JavaScript.

? Syntax & Theory

A CSS Variable is declared as a normal property whose name starts with --. The var() function is used to read its value, with optional fallback: var(--name, fallback).

? View Code Example — Basic CSS Variables
/* Define global CSS variables in :root */
:root {
  --main-bg: #fefefe;
  --main-color: #333333;
  --font-size: 18px;
}

/* Use the variables anywhere in the page */
body {
  background-color: var(--main-bg);
  color: var(--main-color);
  font-size: var(--font-size);
}

/* Example with fallback value */
h1 {
  color: var(--brand-color, #2563eb);
}

? Explanation

The variables --main-bg, --main-color, and --font-size are defined in :root, so they act like global settings. Any element can access them using var().

In the h1 rule, var(--brand-color, #2563eb) uses --brand-color if it exists; otherwise it falls back to #2563eb.

?️ Dynamic Theming Using CSS Variables

You can build light and dark themes by changing variable values on theme container classes. The component uses var() and automatically adapts to the active theme.

? View Code Example — Light & Dark Theme
/* Define theme-specific variables on containers */
.light-theme {
  --bg: #ffffff;
  --text: #111111;
}

.dark-theme {
  --bg: #111111;
  --text: #ffffff;
}

/* Component that reads from the current theme */
.theme-box {
  background: var(--bg);
  color: var(--text);
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 10px;
}

? Explanation

When you wrap an element with class="theme-box light-theme", the variables from .light-theme are used. If you instead use class="theme-box dark-theme", the values from .dark-theme are applied.

By toggling between these theme classes (e.g., on a parent element), you can switch entire sections of the UI between light and dark modes without changing individual CSS rules.

? Using CSS Variables in JavaScript

CSS Variables can be updated dynamically using JavaScript. This is perfect for sliders, color pickers, live previews, or user-controlled themes.

? View Code Example — Update Variable with JavaScript
// Update a global CSS variable at runtime
document.documentElement.style.setProperty("--main-color", "blue");

// Example: read the current value
const currentColor = getComputedStyle(document.documentElement)
  .getPropertyValue("--main-color")
  .trim();

? Explanation

document.documentElement targets the <html> element (same as :root in CSS). Using style.setProperty(), you can change --main-color at runtime, and all elements using var(--main-color) update instantly.

The getComputedStyle() API lets you read the effective value of a variable, which is useful for debugging or syncing UI controls with the current theme.

? Tips & Best Practices

  • Define common styles in :root so they are globally available.
  • Group theme-related variables (colors, shadows, radii) together for easy maintenance.
  • Use JavaScript only when the value must change at runtime; prefer pure CSS variables + classes otherwise.
  • Provide fallbacks inside var() for safer, backward-compatible styling.
  • Organize themes using container classes like .light-theme and .dark-theme.
  • Remember that CSS Variables are resolved at runtime and can be used with functions like calc().

? Try It Yourself

  • Define theme variables in :root (e.g., --primary, --bg, --radius) and apply them to a simple card layout.
  • Override one variable (like --primary) inside a special class (e.g., .warning-card) and see how only those cards change.
  • Use calc() with a variable (e.g., padding: calc(var(--base-space) * 2);) and experiment with different base sizes.
  • Create a small theme switcher in JavaScript that changes --primary-color based on a button click.
  • Use a media query to change a variable (e.g., --font-size) for small screens and observe how the text scales responsively.