Special Offer Diwali Special Bundle Offer: 3 courses for ₹8,999, save ₹9,001 (50% OFF)! Limited seats available. View Bundles →
0% Completed
Tutorials / CSS Tutorial / Chapter 5: Advanced Selectors, Effects & Variables
CSS ⏱ 10 min read

CSS Variables (Custom Properties)

CSS Variables bring real programming power into standard stylesheets, enabling instant theming and dark mode switches.

What is it?

CSS Custom Properties (commonly known as CSS Variables) are entities defined by CSS authors that contain specific values to be reused throughout a document, prefixed with `--` and accessed via `var(--name)`.

Why is it used?

Centralizes design tokens (colors, font sizes, borders, spacing) in one place. Makes switching between Light Mode and Dark Mode seamless with a single attribute toggle.

Detailed Explanation

Defining and Accessing Variables: • Scope: Declaring variables inside `:root` makes them globally accessible everywhere in the document. • Accessing: Use `var(--variable-name, fallbackValue)`. • Theming: Override variables under a `[data-theme="dark"]` attribute selector to change colors across the entire website instantly without rewriting rules.

Syntax Structure

Syntax Blueprint
:root {
  --primary: #1c1c1c;
  --bg: #f7f4ed;
}

body {
  background-color: var(--bg);
  color: var(--primary);
}

Code Example

CSS Code
/* Global Design Tokens */
:root {
  --bg-primary: #f7f4ed;
  --bg-card: #fcfbf8;
  --text-main: #1c1c1c;
  --text-muted: #5f5f5d;
  --border: #eceae4;
  --radius-card: 12px;
}

/* Instant Dark Theme Override */
[data-theme="dark"] {
  --bg-primary: #121212;
  --bg-card: #1c1c1c;
  --text-main: #fcfbf8;
  --text-muted: #a1a1aa;
  --border: #2e2e2e;
}

/* Components automatically adapt to current theme */
body {
  background-color: var(--bg-primary);
  color: var(--text-main);
  transition: background-color 0.25s ease, color 0.25s ease;
}

.card {
  background-color: var(--bg-card);
  border: 1px solid var(--border);
  border-radius: var(--radius-card);
  padding: 20px;
}

Explanation of the Code

• Setting variables on `:root` defines defaults. • When JavaScript adds `data-theme="dark"` to `<html>`, all components referencing `var(--...)` instantly recolor without reloading.

Expected Output

A consistent design system that transitions smoothly between light warm parchment and sleek dark mode.

Real-World Application

Used by GitHub, Lovable, Tailwind CSS, and IGM Computers for effortless dark mode toggling.

Common Mistakes to Avoid

• Forgetting the double hyphens `--` prefix when naming custom properties. • Omitting a fallback value when reading third-party variables (`var(--accent, #000)`).

Quick Practice Challenge

Define a `--brand-color: #2563eb;` in `:root` and use it on a button's background.

Key Takeaways

• Declare custom properties with `--` on `:root`. • Access them using `var(--custom-name)`. • Essential for implementing modern Light/Dark theme switchers.