CSS Variables

Custom properties for dynamic theming.

Introduction

As projects grow, CSS becomes hard to manage. CSS Variables (Custom Properties) solve this by allowing you to store reusable values like colors, spacing, and fonts in one place.

In this chapter, you will learn:

  • How to declare and use CSS variables
  • Global vs local scope
  • Using fallback values
  • Dynamic theming (Light / Dark mode)
  • Best practices for maintainable CSS

Declaring & Using Variables

Variables are declared with two hyphens (--) and used with the var() function.

Syntax
:root {
  --primary-color: #007bff;
  --spacing-md: 16px;
}

button {
  background-color: var(--primary-color);
  padding: var(--spacing-md);
}
Tip: Defining variables in :root makes them available globally across your entire stylesheet.

Scoping & Fallbacks

Local Scope

Variables can be scoped to specific elements.

.card {
  --card-bg: #f8f9fa;
  background-color: var(--card-bg);
}
Fallback Values

Provide a backup value if the variable is missing.

color: var(--text-color, #333); /* Uses #333 if --text-color is undefined */

Real-World Use Cases

1. Color System
:root {
  --primary: #007bff;
  --success: #28a745;
  --danger: #dc3545;
}
.btn-primary { background: var(--primary); }
2. Spacing Consistency
:root {
  --space-sm: 8px;
  --space-md: 16px;
  --space-lg: 24px;
}
.card { padding: var(--space-md); }
3. Dynamic Theming (Light/Dark)
:root {
  --bg: white;
  --text: #333;
}
.dark-theme {
  --bg: #121212;
  --text: #f1f1f1;
}
body {
  background: var(--bg);
  color: var(--text);
}

Common Beginner Mistakes & Best Practices

Common Mistakes
  • Forgetting var() function
  • Redefining variables unnecessarily
  • Using unclear names (e.g., --c1, --color)
Best Practices
  • Define global tokens in :root
  • Use semantic naming (e.g., --text-primary)
  • Group related variables together

Chapter Summary

In this chapter, you learned:

  • How to use CSS variables to store and reuse values.
  • The difference between global (:root) and local scope.
  • How to implement theming and fallback values.
  • Why CSS variables are superior for maintenance and scalability.

You now know how to write scalable, maintainable, professional CSS using variables.