Dev.to WebDev 🛠 Dev 👁 2 📖 1 min read

CSS Custom Properties for Beginners: Variables That Make Theming Easy

CSS custom properties — usually called CSS variables — let you name a value once and reuse it everywhere. Change the name in one place and every button, card, and heading updates. They are the simplest path to a themeabl

CSS custom properties — usually called CSS variables — let you name a value once and reuse it everywhere. Change the name in one place and every button, card, and heading updates. They are the simplest path to a themeable site, including dark mode, with no build step.

Declare them on :root so they are available everywhere:

:root {
  --primary: #2563eb;
  --background: #ffffff;
  --text: #1a1a1a;
  --radius: 8px;
  --spacing: 16px;
}

.button {
  background: var(--primary);
  color: white;
  border-radius: var(--radius);
  padding: 10px var(--spacing);
}

var() takes a fallback as its second argument, which is useful when a variable might not be defined:

.card {
  background: var(--card-bg, #f5f5f5);
}

Dark mode is where variables earn their keep. Override the same names under a class or media query and the whole site flips:

@media (prefers-color-scheme: dark) {
  :root {
    --background: #111827;
    --text: #f3f4f6;
    --primary: #60a5fa;
  }
}

body {
  background: var(--background);
  color: var(--text);
}

Unlike preprocessor variables, custom properties are live: JavaScript can read and change them at runtime, which means a theme toggle is one line:

document.documentElement.style.setProperty("--primary", "#dc2626");

Scope is the other superpower. A variable defined on a component overrides the global one just for that component — a red "danger" card that reuses the same button styles:

.card-danger {
  --primary: #dc2626;
}

Three mistakes beginners make: first, naming variables by value (--blue) instead of by role (--primary) — roles survive a redesign, values do not. Second, over-using variables for one-off values that never repeat. Third, forgetting that custom properties inherit, so a variable set on a parent leaks into children unless overridden.

Ways to extend it: build a full light/dark theme toggle that stores the choice in localStorage, define a spacing scale (--space-1 through --space-8) and use it consistently, and try defining variables inside @media blocks for responsive typography. Once your colours and spacing live in variables, a redesign stops being a search-and-replace job.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.