CSS chapters

Chapter 4 of 17

Custom properties and fallbacks

Try this in our CSS Compiler →

The idea

CSS custom properties begin with -- and participate in the cascade. Read one with var(). They usually inherit, so a component can override a shared value. They are not JavaScript variables: there is no assignment expression or function scope. A fallback is used when the custom property is unavailable or invalid as a custom property.

Worked example

:root { --brand: teal; --space: 12px; }
button { background: var(--brand, navy); padding: var(--space); color: white; }

What to check

Changing --brand changes the button without rewriting its background declaration. An unsuitable substituted value can still invalidate the property using it.

Practice task

Override --brand inside one class and compare the styled element with an element outside that class.

Check your understanding

Explain the result in your own words before changing the example. Change one thing at a time, compare the result with your prediction, and keep the version that demonstrates the concept clearly.

Try it yourself

Output
Ctrl/Cmd+Enter runs · Ctrl/Cmd+S downloads the project · Local auto-save is always on