25. CSS Variables (Custom Properties) - Introduction
CSS Variables (officially called Custom Properties) are one of the most powerful modern features in CSS. They allow you to define reusable values, making large stylesheets DRY (Don't Repeat Yourself) and highly maintainable.
Defining a Variable
Variables are defined using a double hyphen prefix (--). They are typically defined on the :root pseudo-class so they are globally available throughout your document.
css :root { /* Define colors */ --primary-color: #007bff; --secondary-color: #6c757d;
/* Define spacing */ --spacing-md: 1rem; --max-width: 1100px; }
Using a Variable
To retrieve the value of a variable, use the var() function.
css h1 { /* Use the color variable */ color: var(--primary-color); margin-bottom: var(--spacing-md); }
.btn-primary { background-color: var(--primary-color); padding: var(--spacing-md); }
Benefits
- Maintainability: To change your site's primary color, you only change the value once in
:root, and it updates everywhere. - Theming: Variables are essential for implementing features like Dark Mode.
- Readability:
--primary-coloris much clearer than#007bff.