D DevBrainBox

CSS Variables

CSS

What are CSS Variables?

CSS Variables let you store values (like colors, sizes, fonts, etc.) in reusable names, so you can update them in one place and use them throughout your stylesheet.

1. Define a variable

You define variables inside a selector — usually :root so they apply globally.

:root {
  --main-color: #3498db;
  --font-size: 18px;
}

2. Use the variable

You use it with the var() function.

h1 {
  color: var(--main-color);
  font-size: var(--font-size);
}

Why Use CSS Variables?

  • Easy to update global styles (colors, sizes)
  • Keeps code clean and consistent
  • Great for theming (light/dark mode)
  • Reusable across components

Example

:root {
  --primary-color: #ff6347;
  --padding: 20px;
}

.button {
  background-color: var(--primary-color);
  padding: var(--padding);
  border: none;
  color: white;
}

We can change --primary-color in one place and it updates everywhere it’s used!

Scoped Variables

You can also define variables inside specific selectors:

.card {
  --shadow-color: rgba(0, 0, 0, 0.2);
  box-shadow: 0 4px 8px var(--shadow-color);
}

These variables apply only inside .card.

On this page