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

Scoping Custom Properties

How custom properties cascade and inherit, creating scoped variables within specific elements.

Scoping Custom Properties

You'll learn how custom properties can be limited to specific parts of your page, creating localized design systems.

Understanding Scope

While the :root selector creates global custom properties available everywhere, you can also declare custom properties on any element. When you do this, that property and its value are only available to that element and its descendants—not to sibling or parent elements.

Think of it like a family recipe book. If grandma keeps the recipe book at the family home (:root), everyone can use it. But if you write your own recipe on a card and keep it in your kitchen, only you and people in your kitchen (your children/descendants in the DOM) can access it.

How Cascading Works

Custom properties follow the same cascading and inheritance rules as regular CSS properties. If a child element doesn't define a custom property, it inherits the value from its parent. If it does define the same property, it overrides the parent's value for itself and its descendants:

.card {
  --primary-color: blue;
  background: var(--primary-color); /* blue */
}

.card-special {
  --primary-color: red;
  background: var(--primary-color); /* red */
}

Elements inside .card-special will see --primary-color as red, while elements inside regular .card see blue. This scoping allows different components to maintain their own "theme" without conflicts.

Practical Value

Scoped custom properties enable component-level theming—a button component can define its own --button-bg without affecting other buttons elsewhere on the page.

Key Takeaway: Custom properties respect the cascade and can be scoped to specific elements, creating local variables that only affect that element and its descendants.