Course contentsShow
← Web Development
Lesson 468 of 2,9828. Advanced CSS Selectors and FeaturesFree lesson

Declaring and Using Custom Properties

How to define custom properties with -- prefix and reference them using the var() function.

Declaring and Using Custom Properties

You'll learn how to create and use your own reusable CSS values with custom properties.

Now that you understand what custom properties are, it's time to put them into practice. Declaring and using custom properties involves two simple steps: defining them with a special -- prefix, and referencing them with the var() function.

Declaring Custom Properties

To declare a custom property, choose a name (make it descriptive!), prefix it with two dashes (--), and assign it a value. Custom properties are typically declared on the :root selector so they're available throughout your entire stylesheet:

:root {
  --primary-color: #3498db;
  --spacing-unit: 1rem;
  --max-content-width: 1200px;
}

Think of :root as your CSS "storage locker" where you keep values you'll use repeatedly.

Using Custom Properties with var()

To use a custom property, wrap its name (including the --) in the var() function:

.button {
  background-color: var(--primary-color);
  padding: var(--spacing-unit);
}

.container {
  max-width: var(--max-content-width);
  margin-inline: auto;
}

The browser replaces var(--primary-color) with whatever value you declared—in this case, #3498db. Change the value once in :root, and every element using that custom property updates automatically.

Why This Matters

Instead of searching through hundreds of lines to update a color or spacing value in multiple places, you change it once at the source. It's like having a master control panel for your design tokens.

Key Takeaway: Declare custom properties with the -- prefix (usually in :root), then reference them anywhere using var(--property-name) to create maintainable, reusable CSS values.