Variable fallback
Learn to use fallback values in var().
Fallback value
Sometimes a variable may be undefined; the name is mistyped or not added yet. In those cases, you pass a second argument to var(): a fallback value.
Syntax: var(--name, newvalue). If the variable is not found, the browser uses the fallback. Your page stays intact; a safe backup is in place.
When does fallback help?
Two common cases. First: you haven't defined the variable name anywhere yet. Second: you expect a variable from an external stylesheet but that file fails to load.
Example: color: var(--text, #111827);. If --text is undefined, the text becomes dark gray; if defined, the defined value is used. The fallback must be the same type: color for color, length for length.
Exercise Write a var() with fallback
Inside a .uyari selector, add the declaration color: var(--text, #111827);. The variable name is --text, the fallback is #111827.
Show example solution
open a .uyari selector; write color: var(--text, #111827);
Example solution:
.uyari {
color: var(--text, #111827);
}
Test yourself
-
Which correctly writes a fallback inside var()?
color: ?- var(--color #2563eb)
- var(--color; #2563eb)
- var(--color | #2563eb)
- var(--color, #2563eb)
Show answer
var(--color, #2563eb) — Correct! Fallback is comma-separated: var(--name, value).
-
Add a fallback for padding
p { padding: var(--space____; }Show answer
p { padding: var(--space, 16px); } -
Match the scenarios
- --name undefined
- fallback kicks in
- --name defined
- defined value is used
- var(--name, backup)
- fallback syntax
- comma separation
- fallback separator