All topics › Unit 3 · Cascading Style Sheets
Topic 36 · 36 of 43
CSS Variables
All in one: every CSS variable idea, side by side
What this example compares
- The problem:
#E07B1Etyped into seven rules vsvar(--brand)in the same seven - Declare and read:
--tone: ...;+var(--tone)vs the look-alikestone:,background: --brand;,$brandand@brand - Case-sensitive names:
--brandvs--Brandvs--BRAND - One variable, many places:
color,background,border-left,border-radius,padding,font-family, with colours, lengths and a font list - Scope: declared on
:rootvs inside.cardvs read in a.footeroutside it - Override for one component:
.card.done,.card.progress,.card.lateand a plain.card - Fallback:
var(--brand)vs the typovar(--brnad)vsvar(--brnad, #333)vsvar(--brand, #333)vs the nestedvar(--card-accent, var(--brand)) - Themes: light values vs
.darkvs@media (prefers-color-scheme: dark) - Live in the browser:
:hover, one line of JavaScript and DevTools change or show a variable; a Sass$brandcannot - Naming:
--brandand--danger(by job) vs--orange(by colour) - Project step 14: Asha Kumar's page built from twelve design tokens
Point at any word in the code to see what it means (tap on a phone); click a word to keep its meaning on screen. Read the comment above each numbered panel, press Run, then Edit & experiment to try the TRY lines yourself.
Loading the example…
What you should see
You should see eleven panels (scroll inside the result to reach them all). In panel 1 the two little pages look exactly alike. In panel 2 the bars are blue, empty, orange, empty, empty, empty; in panel 3 orange, blue, empty. Panel 4 shows the same line six ways: orange text, a cream fill, an orange left edge, round corners, extra space and a Georgia font. In panel 5 the first bar is green, the second blue and the third empty. Panel 6 shows a green, an orange, a red and a grey card. In panel 7 the word CSE326 is orange, light grey, almost black, orange, orange and green. Panel 8 shows a light card, a dark card, and a third that follows your device (light on a light-mode device). In panel 9 the first bar turns green while you hover it, the button switches the box between light and dark, and the last bar never changes. Panel 10 shows an orange, a red and a blue button, and panel 11 is Asha Kumar's course page. There is one line of JavaScript, but nothing is printed, so the Console stays empty.
Quick check: in panel 7, why is the word in box 2 light grey and not black, although nothing in its rule says light grey?
Because var(--brnad) is a typo, so its color line becomes invalid and the word takes the colour it inherits from its paragraph, which is light grey. No error is shown. Box 3 has the same typo but adds a fallback, var(--brnad, #333), so it gets #333 instead.