Fallback Values for CSS Variables

What Happens if a Variable Is Not Defined

If var() references a custom property that was never declared anywhere in scope, the property using it fails to apply at all - it does not silently fall back to some default CSS value on its own.

Providing a Fallback Value

.btn {
  background: var(--brand-color, #1d4ed8);
}

The second argument to var() is used only if --brand-color is not defined anywhere in scope - a safety net for components that might be dropped into a page that has not set up that variable.

When Fallbacks Are Genuinely Useful

  • Building a reusable component library where consuming projects may or may not define certain theme variables.
  • Writing defensive base styles that should still look reasonable even if a later theme file fails to load.
  • Providing a safe default while a design system's variables are still being finalized.

Chaining Multiple Fallbacks

.btn {
  background: var(--btn-color, var(--brand-color, #1d4ed8));
}

Fallbacks can be nested: this tries a very specific --btn-color first, falls back to a more general --brand-color next, and finally falls back to a hardcoded value if neither is defined anywhere.

A Different Case: An Invalid Value

A fallback only helps when a variable is completely undefined. If a variable is defined but holds an invalid value for that property (for example, text where a color is expected), the property is treated as if it were never set at all - the fallback in var() does not catch this case, since the variable itself is technically defined.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Continue reading

All CSS notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.