Retour au cours

Lesson 25: CSS Variables (Custom Properties) - Introduction

**La Maîtrise de CSS : De zéro à expert en 100 leçons** *(Alternative, slightly punchier version using a common French idiomatic structure for full coverage: CSS : Maîtrisez l'essentiel en 100 leçons, but the first option is closer to the original progression.)*

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

  1. Maintainability: To change your site's primary color, you only change the value once in :root, and it updates everywhere.
  2. Theming: Variables are essential for implementing features like Dark Mode.
  3. Readability: --primary-color is much clearer than #007bff.