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

What are CSS Custom Properties?

Understanding CSS variables, their syntax with --, and how they differ from preprocessor variables.

What are CSS Custom Properties?

You'll learn what CSS variables are, how to define them, and why they're different from variables in preprocessors like Sass.

What Are CSS Custom Properties?

CSS Custom Properties, commonly called CSS variables, are entities you define in your CSS that hold specific values you can reuse throughout your stylesheet. Think of them as containers with labels—you store a value once, give it a meaningful name, and then reference that name wherever you need that value.

Unlike preprocessor variables (like those in Sass or Less) that are compiled away before the browser sees your CSS, custom properties are live, dynamic values that exist in the browser's rendering engine. This means they can be changed on the fly with JavaScript, inherit through the cascade, and respond to media queries.

Syntax: The Double-Dash Pattern

Custom properties are defined using a double-dash prefix (--):

:root {
  --primary-color: #3498db;
  --spacing-unit: 1rem;
}

You retrieve their value using the var() function:

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

The :root selector is common for global variables, but you can define custom properties on any element. They cascade and inherit to descendants, just like regular CSS properties.

Key Differences from Preprocessors

While Sass variables look similar ($primary-color), they're fundamentally different:

  • Preprocessor variables are replaced during build time and don't exist in the final CSS
  • Custom properties are real CSS that browsers understand natively and can be manipulated at runtime

Key Takeaway: CSS Custom Properties are native browser variables defined with -- and accessed with var(), offering dynamic runtime behavior unlike preprocessor variables that are compiled away.