CSS Variables, also known as Custom Properties, are a modern way to manage values in your stylesheet. They allow you to define reusable values like colors, spacing, and fonts, and update them in one place. This makes your CSS cleaner, more maintainable, and easier to theme.

What are CSS Variables?

CSS variables are defined using the prefix inside a CSS selector, usually: root for global variables. They can be reused throughout your styles using the var() function.

Example

:root {
  --primary-color: #4CAF50;
  --padding: 16px;
}

button {
  background-color: var(--primary-color);
  padding: var(--padding);
}

Why Use CSS Variables?

CSS Variables vs Preprocessor Variables

Unlike preprocessor variables in SASS or LESS, CSS variables are dynamic and can be changed at runtime. This makes them more powerful for interactive features like theming.

Real-World Example: Dark and Light Theme

:root {
  --bg-color: white;
  --text-color: black;
}

@media (prefers-color-scheme: dark) {
  :root {
    --bg-color: black;
    --text-color: white;
  }
}

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

Tips & Best Practices

Final Thoughts

CSS Variables are a powerful tool for building scalable and theme-friendly websites. They promote consistency and efficiency in writing CSS. If you're not using them yet, now is the time to start!