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

Fallback Values in var()

Providing fallback values in var() function for defensive CSS and handling undefined properties.

Fallback Values in var()

You'll learn how to provide backup values when using CSS custom properties to make your styles more resilient.

The Safety Net for Your Variables

When you use var() to reference a CSS custom property, there's always a chance that property isn't defined—maybe due to a typo, scoping issue, or intentional omission. Without a fallback, the browser treats the declaration as invalid. Fallback values give you a "plan B."

Think of it like ordering at a restaurant: "I'll have the salmon special, but if you're out, I'll take the chicken instead."

How Fallback Values Work

The var() function accepts a second argument—a fallback value that kicks in if the custom property is undefined:

.button {
  background-color: var(--primary-color, blue);
}

If --primary-color isn't defined anywhere in scope, the button gets blue as its background instead of breaking.

Why This Matters

Fallbacks are defensive CSS. They protect your design from:

  • Undefined variables: when a custom property simply doesn't exist
  • Scoping gaps: when you reference a variable outside its scope
  • Progressive enhancement: older browsers that don't support custom properties can use the fallback

You Can Chain Fallbacks

Fallbacks can even reference other custom properties:

.card {
  color: var(--text-color, var(--fallback-text, black));
}

If --text-color fails, try --fallback-text. If that fails, use black.

Key Takeaway: Always provide fallback values in var() when possible—it makes your CSS more robust and prevents layout breaks when custom properties are missing or out of scope.