css · level 3 · unit 1 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Give var() a second value for when the token is missing.
var(--accent, crimson) reads --accent, and if nothing above sets it, uses crimson instead. That second value is the fallback, the same idea as a font list. Components shared between sites rely on it.
There is a trap. If the token exists but holds the wrong kind of value, like --gap: red used for padding, the fallback is not used. The browser only spots the problem when it works out the , the final value for each property.
By then it is too late to try an earlier declaration. The property drops to its , the value it has before any CSS, or inherits if it normally does.
<span class="badge">Sold out</span> .badge {
padding: 2px 8px;
color: white;
background-color: var(--accent, crimson);
} Press show my page to see it here.
Add :root { --accent: navy; } above the rule and run it again to see the token beat the fallback.
guess first
The token holds the wrong kind of value. What wins?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<p class="alert">The server is down.</p> :root {
--space: crimson;
}
.alert {
padding: 20px;
padding: var(--space, 8px);
background-color: gold;
}
your turn
Your turn. Make a shared button safe on any site.
This button may land on a site that never sets --brand. Add a dark fallback colour of your choice inside the var(), so white text stays readable.
the page you’re styling
<button class="btn">Subscribe</button>your css
Press show my page to see it here.
- the button has a background colournot checked yet
- the button is not white on whitenot checked yet
fix it
The card lost its padding. Can you fix it?
the page you’re styling
<div class="card">Your order has shipped.</div>your css
Press show my page to see it here.
- the card has 16px of paddingnot checked yet
- the padding reaches every sidenot checked yet
- The token exists, so the browser never tries a fallback. Look at what the token holds.
paddingneeds a length. A bare number is the wrong kind of value.- Add the unit:
--space: 16px;, then press run.
nailed it
you gave your tokens a safety net. :D
var(--token, fallback)covers a missing token.- A token with the wrong kind of value skips the fallback.
- Then the property drops to its initial value.
new words in your collection
- computed value
- initial value
This lesson isn’t saved. A free account remembers every lesson you finish.