Back to Curriculum

CSS Variables

📚 Lesson 9 of 16 ⏱️ 25 min

CSS Variables

25 min

CSS Variables, officially known as Custom Properties, allow you to store specific values (like colors, fonts, or sizes) in a reusable variable. This brings the power of programming variables natively to CSS.

You declare a variable using the double hyphen prefix (e.g., `--main-color: #333;`) usually within the `:root` selector to make it global. You then use the `var()` function to retrieve that value (e.g., `color: var(--main-color);`).

The real power of CSS variables is that they are dynamic. Unlike preprocessor variables (Sass/Less) which compile to static values, CSS variables can be updated live by JavaScript or overridden by media queries. This makes features like 'Dark Mode' incredibly easy to implement.

They also respect the cascade, meaning you can redefine a variable inside a specific component to change its local styling without affecting the rest of the site.

Key Concepts

  • Variables store reusable values.
  • Syntax: `--name: value` to set.
  • Syntax: `var(--name)` to use.
  • Scope: Global (`:root`) or Local (selector).
  • Dynamic: Can be changed by JS or Media Queries.

Learning Objectives

Master

  • Declaring and using custom properties
  • Understanding variable scope and inheritance
  • Implementing color themes
  • Using fallback values in `var()`

Develop

  • Systematic design thinking
  • Maintainable codebase architecture
  • Dynamic styling capabilities

Tips

  • Define your design tokens (colors, spacing) in `:root`.
  • Use semantic names (`--primary-text`) rather than descriptive ones (`--blue-text`).
  • Provide a fallback value: `var(--color, black)`.
  • Use variables for values that change often or are used repeatedly.

Common Pitfalls

  • Forgetting the double hyphen `--` prefix.
  • Trying to use variables in media query selectors (not supported).
  • Over-engineering by making everything a variable.
  • Browser support issues (only relevant for very old browsers like IE).

Summary

  • CSS Variables enable reusable, dynamic values.
  • They simplify theming and maintenance.
  • They follow the cascade and scoping rules.
  • Essential for modern, scalable CSS.

Exercise

Define a primary color variable and use it to style a heading.

:root {
  --primary-color: #ff6347;
}

h1 {
  color: var(--primary-color);
}

Exercise Tips

  • Create a dark mode by overriding variables in a media query: @media (prefers-color-scheme: dark) { :root { --primary-color: #ff9999; } }.
  • Use variables for spacing: --spacing-unit: 8px; margin: calc(var(--spacing-unit) * 2);
  • Override variables in component scopes for theme variations.
  • Change variables dynamically with JavaScript for interactive theming.

Code Editor

Output