CSS Variables

What Are CSS Variables?

CSS Variables (also called custom properties) let you store values in one place and reuse them throughout your stylesheet. They make your code cleaner, easier to maintain, and perfect for theming (light/dark modes).

:root {
  --main-color: #64b5f6;
  --bg-dark: #121212;
  --spacing: 12px;
}

button {
  background: var(--main-color);
  margin: var(--spacing);
}
      

Why Use CSS Variables?

How to Create a Variable

Variables must be inside a selector. The most common place is :root because it applies globally.

:root {
  --text-color: #e0e0e0;
  --card-bg: #1e1e1e;
}
      

How to Use a Variable

You use the var() function to access a variable:

p {
  color: var(--text-color);
}
      

Fallback Values

If a variable fails, you can provide a fallback:

p {
  color: var(--missing-var, red);
}
      

Dynamic Variables (Changing at Runtime)

You can update CSS variables with JavaScript to create dynamic themes.

document.documentElement.style.setProperty('--main-color', '#ff0099');
      

Dark Mode Example

:root {
  --bg: #ffffff;
  --text: #000000;
}

.dark {
  --bg: #121212;
  --text: #e0e0e0;
}

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

What's Next?

Now that you understand CSS Variables, you’re ready to start using them for themes, design systems, and cleaner UI work.