CSS  

Mastering Custom Properties (CSS Variables)

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?

  • Centralized control over design tokens (colors, spacing, etc.)
  • Easier to update values across the whole project
  • Useful for dark mode, themes, and responsive design
  • Reduces redundancy in code

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

  • Use: root to define global variables.
  • Use naming conventions like --color-primary, --font-base.
  • Fall back to a value in var() like var(--gap, 10px).
  • Group related variables together for the organization.

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!