T2 CSS · Lesson 10
CSS variables
Naming a value once with a custom property, and reading it with var(); how far a variable reaches; fallbacks, and why a missing variable wipes out an earlier line; sums with calc(); and light and dark themes built from a few role names.
- name a value with a custom property, and use it everywhere with var()
- say how far a variable reaches, and override it for one part of a page
- give a variable a fallback, and explain what a missing variable does
- do sums with calc(), and build sizes from variables
- build light and dark themes from role names, checking contrast in each
The back cover
A long style sheet repeats the same values many times: a brand colour here, a spacing there. Change one and you must hunt down every copy. CSS variables give each value a name, written once and used everywhere, like the price list by a shop's till.
These pages show how to name a value and read it, and how far a variable reaches down the page. They show what happens when a variable is missing, how calc() does sums with mixed units, and how a few variables make a whole light or dark theme.
Before you start
The story: Two hundred threads
The Fair's council has changed its mind: the board's colour is to be indigo, not marigold. Corin sighs and starts down the sheet, changing marigold to indigo wherever he finds it. It is in buttons, borders, headings and links, about two hundred times. By evening he has missed eleven, and the board looks patched.
The warden has another wish. The great glass by the gate should darken after sunset, so that the board does not dazzle people at night.
Meher leads him to the dye room. "We do not dye each thread by hand," she says, and points at one great vat. "Every thread comes from here. Change the vat, and the whole cloth changes with it."
Every sheet so far has written its values out in full: the same teal in ten places, the same 16 pixels of space in twenty. That works for a small page. On a real site it means that one change of colour is an evening's work, and a few places are always missed. This last CSS lesson gives a value a name, so that it is written once and used everywhere. It builds on these ideas; each has a tiny example.
| What you already know | A tiny example | Where it comes back |
|---|---|---|
| A rule sets a property to a value. | color: teal; | A variable is a property you name yourself. |
| Some properties pass down from parent to child. | A colour set on body reaches every paragraph. | Variables pass down in the same way. |
| The inherit word and initial values. | A div's background starts transparent. | A broken variable falls back to these. |
| The cascade picks a winner. | A later rule beats an earlier one of equal weight. | A variable's value is chosen by the same rules. |
| The html element is the top of the page. | Everything else sits inside it. | Variables for the whole page are set there. |
| A browser drops a declaration it cannot read. | color: bluee; is ignored, and the earlier colour stays. | A broken variable does not behave like this, and that surprises everyone. |
| Mixing % and px needs care. | A 100% wide box with 40px of padding overflows. | calc() does the sum for you. |
| Media queries change rules on some screens. | @media (min-width: 600px). | Changing one variable in a query changes everything that uses it. |
| Visitors can ask for things. | prefers-reduced-motion reads a device's setting. | prefers-color-scheme reads whether it is set to dark. |
| Contrast of 4.5 to 1 for text. | Dark grey on white passes. | A dark theme must keep it too. |
By the end of this lesson you will be able to:
- name a value once with a custom property, and use it everywhere with var();
- say how far a variable reaches, and override it for one part of a page;
- give a variable a fallback, and explain what happens when one is missing;
- do sums in CSS with calc(), and build sizes from variables;
- build a light and a dark theme by changing only a few variables.
In one line
A custom property names a value once, so that a change in one line reaches the whole page; you need inheritance, the cascade and the idea of a value that the browser cannot use.
A name for a value: custom properties
At a glance
A shop keeps its prices on one sheet by the till. When sugar costs more, one line changes, and every bill after that is right. A custom property, usually called a CSS variable, is that sheet: --brand: teal names a value, and var(--brand) reads it wherever it is needed.
Set on :root, a variable reaches the whole page, so one change reaches every use. Names are case-sensitive, so --Brand and --brand are two different variables. A good name says the job, such as --accent, rather than the colour.
Take a guess: If a page uses var(--brand) in twenty places, how many lines must change to give it a new brand colour?
A shop keeps its price list on one sheet by the till. When the price of sugar goes up, the shopkeeper changes one line, and every bill from then on is right. Imagine instead that the price were written on every bag: each change would mean a walk round the whole shop, and some bags would be missed. A custom property, usually called a CSS variable, is the sheet by the till.
A property whose name you choose, starting with two dashes, such as --brand. It holds a value, and does nothing by itself. Any rule can then ask for that value with var(--brand).
One name, four uses
<!DOCTYPE html>
<style>
:root { --brand: teal; }
body { margin: 0; }
h1 { color: var(--brand); }
a { color: var(--brand); }
button { background-color: var(--brand); color: white; }
hr { border-color: var(--brand); }
</style>
<h1>Asha Stores</h1>
<a href="#offers">Today's offers</a>
<hr>
<button>Add to cart</button>
Checked in Chrome
- the heading is teal
- so is the link
- so is the button
- and the line
Read the two halves aloud. --brand: teal; says "brand means teal". var(--brand) says "the value of brand". Now the council changes its mind. One word changes, in one line:
The same sheet, one word changed
<!DOCTYPE html>
<style>
:root { --brand: indigo; }
body { margin: 0; }
h1 { color: var(--brand); }
a { color: var(--brand); }
button { background-color: var(--brand); color: white; }
hr { border-color: var(--brand); }
</style>
<h1>Asha Stores</h1>
<a href="#offers">Today's offers</a>
<hr>
<button>Add to cart</button>
Checked in Chrome
- the heading is indigo
- so is the link
- so is the button
- and the line: one word changed all four
What is :root?
:root is a selector for the top element of the page, which is <html>. Everything else sits inside it, and variables pass down from parent to child, so a variable set on :root can be read everywhere on the page. The next section shows how that works.
Good names
| Name | Good? | Why |
|---|---|---|
--accent | yes | says what the colour is for |
--text-muted | yes | lower case, with hyphens between words |
--space-large | yes | says the job, not the number |
--teal | no | if the brand turns indigo, the name becomes a lie |
--16px | no | the same problem: a name that is its own value |
A memory aid
Name the job, not the look. --accent can change colour for ever and stay true.
Capital letters count
Most of CSS ignores capitals, but variable names do not. --Brand and --brand are two different variables. A rule asking for the wrong one finds nothing.
<!DOCTYPE html>
<style>
:root { --Brand: teal; }
h1 { color: var(--brand); }
</style>
<h1>Asha Stores</h1>
Checked in Chrome
- (the slip: --Brand was set and --brand was asked for, so the heading stays black)
Any value at all
A variable can hold any value: a colour, a length, a list of fonts, a shadow, a time. Whatever is written after the colon is kept as it is, and handed over when asked for.
<!DOCTYPE html>
<style>
:root {
--radius: 8px;
--font-main: Georgia, serif;
--speed: 200ms;
--lift: 0 2px 6px rgb(0 0 0 / 30%);
}
body { margin: 0; font-family: var(--font-main); }
.card { border-radius: var(--radius); box-shadow: var(--lift); transition: transform var(--speed); }
</style>
<div class="card">Masala tea, ₹15</div>
Checked in Chrome
- a length
- a list of fonts
- a time
- and a whole shadow
Worked example 1
A sweet shop's page uses the same deep orange, rgb(200, 90, 0), for its heading, its price tags and its button. The owner is thinking of changing the colour. Rewrite the sheet so that the next change takes one line.
What we have: one colour, used in three rules
What we need: a variable with a good name, and three rules that ask for it
The plan: set --accent on :root, because the whole page needs it; replace each colour with var(--accent)
- The name says the job:
--accent, not--orange, because the colour may change. - It goes on
:root, so that every rule can read it. - Each of the three rules now asks for it by name.
<!DOCTYPE html>
<style>
:root { --accent: rgb(200, 90, 0); }
body { margin: 0; }
h1 { color: var(--accent); }
.price { color: var(--accent); }
button { background-color: var(--accent); color: white; }
</style>
<h1>Sharma Sweets</h1>
<p class="price">Kaju katli, ₹900 a kilo</p>
<button>Order now</button>
Checked in Chrome
- the heading has the colour
- so does the price
- and the button
- from the one line on :root
:root { --accent: rgb(200, 90, 0); }, then var(--accent) in each of the three rules. The next change of colour is one line.
Check: all three read the same colour, from the one line.
When you are stuck: custom properties
A variable that does nothing: is it written with two dashes? Is it asked for with var()?
A rule that finds nothing: compare the two names letter by letter, capitals too.
Not sure where to set it: on :root, if the whole page needs it.
Your turn
How does every custom property's name begin?Tap to reveal
- How many dashes?
With two dashes, such as --brand.
Are --Accent and --accent the same variable?Tap to reveal
- Unlike most of CSS.
No: variable names are case-sensitive.
Why is --accent a better name than --teal?Tap to reveal
- What if the colour changes?
It names the job, so it stays true when the colour changes.
Did you know?
Variables were once spelled var-
CSS variables were first spelled another way. A W3C draft of 10 April 2012 said that any property name starting with the prefix var- was a variable property, and it noted that others had suggested a dollar sign, as in $foo. Today's standard uses two dashes instead: a custom property is any property whose name starts with --.
Why it fits here: This topic's --brand is the final spelling, after var- and the dollar sign were tried.
Sources: W3C: CSS Variables Module, Working Draft 2012; W3C: CSS Custom Properties for Cascading Variables
CSS will never claim the double dash
The double dash is a promise. The Custom Properties standard says these properties are only for authors and users, and that CSS will never give them a meaning of its own, so a future version of CSS cannot clash with your names. Only the bare -- is kept back for future use. And --foo and --FOO are two distinct properties.
Why it fits here: It is why this topic's names are safe for good, and why their capital letters matter.
In one line
A custom property such as --brand: teal names a value, var(--brand) reads it, and setting it on :root lets the whole page use it, so one change reaches every use; names are case-sensitive, and should say the job.
How far a variable reaches
At a glance
A family rule, dinner at eight, passes to the children; one of them may set dinner at nine in a home of their own. Variables pass down the page the same way. A custom property is inherited: the element it is set on and everything inside it can read it.
An element inside can set the same variable to a new value, and that value holds for everything inside that element. So one rule can mean different things in different places. Media queries and states can change a variable, but a query's condition cannot read one.
Take a guess: If :root sets --gap: 8px and a card sets --gap: 24px, which value do the card's children read?
A family has a rule at home: dinner at eight. The children grow up with it. But one of them, in a home of their own, may set dinner at nine, and everyone in that home follows the new rule, while the old home carries on as before. Variables pass down the page in the same way.
A custom property is inherited: the element it is set on and everything inside that element can read it. An element further in can set a new value, which then applies to it and everything inside it.
<!DOCTYPE html>
<style>
:root { --brand: teal; }
body { margin: 0; }
.sale { --brand: crimson; }
h2 { color: var(--brand); }
</style>
<h2 class="plain">Daily needs</h2>
<div class="sale">
<h2 class="off">Diwali sale</h2>
</div>
Checked in Chrome
- outside the sale, the heading reads teal from :root
- inside it, the nearer value wins: crimson
There is one rule for h2, and it never changed. The colour differs because var(--brand) is looked up from where each heading sits. This is what no plain value can do: the rule stays the same, and its meaning changes with the place.
A variable passes down only. A box beside the one that set it cannot see it.
<!DOCTYPE html>
<style>
.first { --c: teal; }
.second { color: var(--c); }
</style>
<p class="first">Rice</p>
<p class="second">Dal</p>
Checked in Chrome
- (the slip: the variable was set on a neighbour, not a parent, so Dal finds nothing and stays black)
One component, many variations
This makes variations very tidy. The button's rule asks for variables; each variation only sets them.
<!DOCTYPE html>
<style>
:root { --accent: teal; }
body { margin: 0; }
.btn { --btn-bg: var(--accent); padding: 8px; color: white; background-color: var(--btn-bg); }
.btn.danger { --btn-bg: crimson; }
.btn.quiet { --btn-bg: dimgrey; }
</style>
<button class="btn a">Buy</button>
<button class="btn danger">Delete</button>
<button class="btn quiet">Later</button>
Checked in Chrome
- the plain button takes the accent
- the danger button only changes --btn-bg
- and so does the quiet one
Changing a variable in a media query
A variable can be set again inside a media query, and every rule that uses it follows. One line can resize the whole page's spacing. The condition itself cannot use a variable: @media (min-width: var(--wide)) does not work, because a query belongs to no element, so there is nowhere to read a variable from.
<!DOCTYPE html>
<style>
:root { --gap: 8px; }
@media (min-width: 600px) {
:root { --gap: 24px; }
}
body { margin: 0; }
.shop { display: grid; gap: var(--gap); }
.card { padding: var(--gap); }
</style>
<div class="shop"><div class="card">Rice</div><div class="card">Dal</div></div>
Checked in Chrome
- at 800: 24px in both places
- at 375: 8px in both places, from one line
Changing a variable on a state
A hover rule can change just the variable, and a transition on the property that uses it still plays, because that property's value has changed.
<!DOCTYPE html>
<style>
body { margin: 0; }
.card { --c: rgb(200, 200, 200); background-color: var(--c); transition: background-color 200ms linear; }
.card:hover, .card:focus { --c: rgb(255, 215, 0); }
</style>
<button class="card">Masala tea</button>
Checked in Chrome
- given focus, the colour is halfway at 100ms, as in the transitions lesson
Worked example 2
A site has an ordinary card and a "festival" card. Both have the same rule for their border, their heading and their tag, but the festival card's three colours should all be saffron, rgb(255, 153, 51), and the ordinary card's teal. Write it with one variable and as few rules as you can.
What we have: one set of rules, two colours
What we need: a variable the rules read, and one line that changes it for the festival card
The plan: read --card-colour in every rule; set teal on .card, and set saffron on .card.festival
- The rules for border, heading and tag each ask for
var(--card-colour). - The ordinary value goes on
.card, so that it passes to the heading and tag inside. .card.festivalsets a new value. Nothing else changes.
<!DOCTYPE html>
<style>
body { margin: 0; }
.card { --card-colour: teal; border: 2px solid var(--card-colour); }
.card.festival { --card-colour: rgb(255, 153, 51); }
.card h2 { color: var(--card-colour); }
.card .tag { color: var(--card-colour); }
</style>
<div class="card a"><h2>Rice</h2><span class="tag">₹60 a kilo</span></div>
<div class="card festival"><h2>Sweets</h2><span class="tag">₹500 a box</span></div>
Checked in Chrome
- the ordinary card is teal
- the festival heading is saffron
- and so are its tag and border, from one line
.card { --card-colour: teal; } .card.festival { --card-colour: rgb(255, 153, 51); }, and every colour rule reads var(--card-colour).
Check: the browser read teal in the ordinary card and saffron in all three places of the festival card.
Worked example 3
A page uses one spacing value in forty places: card padding, grid gaps, section margins. It should be 8 pixels on phones and 16 from 600 pixels up, and later the owner may want 20. What is the least you can write?
What we have: one spacing value used everywhere, and a change at 600
What we need: a variable, and a query that changes only that variable
The plan: set --space on :root, use var(--space) in the forty places, and set it again inside the query
- The forty rules each ask for
var(--space), so none of them needs a query of its own. - The query is one line. Changing 16 to 20 later is one word.
<!DOCTYPE html>
<style>
:root { --space: 8px; }
@media (min-width: 600px) {
:root { --space: 16px; }
}
body { margin: 0; }
.card { padding: var(--space); margin-bottom: var(--space); }
</style>
<div class="card">Rice</div>
Checked in Chrome
- at 800: 16px
- at 375: 8px
:root { --space: 8px; } @media (min-width: 600px) { :root { --space: 16px; } }, and var(--space) in the forty places.
Check: the same rule measured 8 at 375 and 16 at 800.
When you are stuck: variable scope
A rule that finds nothing: is the variable set on this element or one of its ancestors? Neighbours do not count.
The wrong value: look for a nearer ancestor that sets it again.
A media query that ignores a variable in its condition: conditions cannot read variables; write the number.
Your turn
A variable is set on .card. Can a p inside .card read it?Tap to reveal
- It passes down.
Yes: everything inside can.
Can the box next to .card read it?Tap to reveal
- Only inside.
No: a variable passes down only.
Can @media (min-width: var(--wide)) work?Tap to reveal
- A query looks at the screen.
No: write the number in the condition.
Did you know?
var() works only in values
var() works only inside a property's value. The Custom Properties standard says it cannot be used as a property name, in a selector, or anywhere else besides a property value. That is why a media query's condition, such as (min-width: var(--wide)), cannot read a variable.
Why it fits here: It is the rule behind this topic's note that a query's condition cannot read a variable.
Typed variables can glide
An ordinary variable cannot glide: the standard gives custom properties a discrete animation type, so they jump from one value to the next. The @property rule changes that. It registers a variable with a syntax, its type, and an inherits setting, and both are required. A registered variable then animates by its type, so a colour can fade smoothly.
Why it fits here: It extends this topic's variables: with @property, a variable can even be told not to inherit.
Sources: W3C: CSS Custom Properties for Cascading Variables; W3C: CSS Properties and Values API Level 1
In one line
A variable passes down to everything inside the element that sets it, and a nearer value overrides it there, so one rule can mean different things in different places. Media queries and states can change a variable, but a query's condition cannot read one.
When a variable is missing
At a glance
A recipe says: add curry leaves, or if you have none, a pinch of mustard seeds. The second half is a fallback, a plan for when the first thing is not there. var() takes one too: var(--accent, teal) reads as the value of accent, or teal if there is none.
With no value and no fallback, the property acts as if it had never been set. It takes its parent's value or its starting value, and an earlier line for the same property does not come back.
Take a guess: If color: red comes before color: var(--missing) with no fallback, is the text red?
A recipe says: "Add curry leaves, or if you have none, a pinch of mustard seeds." The second half is a fallback, a plan for when the first thing is not there. var() takes one too.
<!DOCTYPE html>
<style>
body { margin: 0; }
h1 { color: var(--accent, teal); }
h2 { font-family: var(--font-main, Georgia, serif); }
h3 { color: var(--a, var(--b, teal)); }
</style>
<h1>Asha Stores</h1>
<h2>Offers</h2>
<h3>Today</h3>
Checked in Chrome
- --accent is not set, so the fallback, teal, is used
- everything after the first comma is the fallback, so a list of fonts works
- and a fallback can itself be a var(): a, or else b, or else teal
Read var(--accent, teal) aloud as "the value of accent, or teal if there is none". Fallbacks suit a component used on many sites: it works alone, and any page can set the variable to dress it.
With no value and no fallback: the surprise
You learned that a browser drops a declaration it cannot read, and the earlier one stays. Here is that rule at work: the misspelt colour is thrown away, and red remains.
<!DOCTYPE html>
<style>
p { color: red; color: bluee; }
</style>
<p>Rice</p>
Checked in Chrome
- bluee is not a colour, so it is dropped, and red stays
Now the same pair with a missing variable. You would expect the same result. Look what happens.
<!DOCTYPE html>
<style>
p { color: red; color: var(--nope); }
</style>
<p>Rice</p>
Checked in Chrome
- (the surprise: the text is black, not red; the earlier rule does not come back)
The reason lies in the order of the browser's work. When it reads the sheet, it cannot know what a var() will hold, so it accepts the line, and the line replaces color: red. Only later, working out the styles of this paragraph, does it find no value. By then, red has gone. The line is now called invalid at computed-value time, and the property behaves as if it had never been set.
| Kind of property | What it gets instead | Example |
|---|---|---|
| one that passes down, such as color | the parent's value | the text takes its parent's colour, here black |
| one that does not, such as background-color | its initial value | the background is transparent |
<!DOCTYPE html>
<style>
body { color: navy; }
p { background-color: red; background-color: var(--nope); color: var(--nope); }
</style>
<p>Rice</p>
Checked in Chrome
- the colour passes down from body: navy
- the background has nothing to inherit, so it is transparent
The same happens when a variable holds the wrong kind of value. The browser cannot tell until it uses it.
<!DOCTYPE html>
<style>
:root { --gap: 10px; }
p { color: red; color: var(--gap); }
</style>
<p>Rice</p>
Checked in Chrome
- (the slip: 10px is no colour, and again the earlier red does not come back)
A memory aid
A bad value is dropped; a bad var() wipes the slate. Give a fallback wherever a variable may be missing.
A variable is not glued to a unit
A variable holds its value as a whole piece. It cannot be stuck to letters beside it, so var(--n)px is not 30px. The next section shows the right way, with calc().
<!DOCTYPE html>
<style>
:root { --n: 30; }
body { margin: 0; }
.bar { width: var(--n)px; height: 20px; }
</style>
<div class="bar"></div>
Checked in Chrome
- (the slip: the width is dropped, and the bar stays the full 800 wide)
Giving a variable a type: @property
A plain variable is only text to the browser, which is why it cannot warn about a wrong kind of value, and why it cannot change smoothly. The @property rule registers a variable with a type, a starting value and whether it passes down. A registered variable can be animated by itself.
<!DOCTYPE html>
<style>
@property --angle {
syntax: "<angle>";
inherits: false;
initial-value: 0deg;
}
body { margin: 0; }
.dial { width: 60px; height: 60px; transform: rotate(var(--angle)); transition: --angle 200ms linear; }
.dial.on { --angle: 90deg; }
</style>
<div class="dial">Tap</div>
Checked in Chrome
- the variable itself is changing over time
You will rarely need this, but it is good to know that the door is there.
Worked example 4
A "Buy" button is written for use on many pages. On pages that set --accent it should use that colour, and on pages that do not it should still be a readable teal, never a button with no background. Write its rule, and explain what would happen without the fallback.
What we have: a variable that may be missing, on a property that does not pass down
What we need: a rule that works on both kinds of page
The plan: var(--accent, teal): the fallback covers the pages with no variable
- Without a fallback, a page with no
--accentwould make the background transparent, its initial value, and the white text would vanish on a white page. - With
var(--accent, teal), those pages get teal.
<!DOCTYPE html>
<style>
body { margin: 0; }
.own { --accent: crimson; }
.buy { color: white; background-color: var(--accent, teal); }
</style>
<button class="buy plain">Buy</button>
<div class="own"><button class="buy">Buy</button></div>
Checked in Chrome
- with no variable: teal, from the fallback
- with the variable set: crimson
.buy { background-color: var(--accent, teal); }. Without the fallback, the background would be transparent on pages with no --accent.
Check: the browser drew teal on the page with no variable and crimson where it was set.
When you are stuck: missing variables
A property that seems to vanish, though an earlier line sets it: a var() in a later line has no value.
Not sure what value a variable has here: in DevTools' Styles panel, hold the pointer over the var() and it shows the value.
A number that will not take a unit: write calc(var(--n) * 1px), not var(--n)px.
Your turn
What is the value of var(--x, 10px) when --x is not set?Tap to reveal
- The fallback.
10px.
After color: red; color: var(--nope); does red stay?Tap to reveal
- The browser accepts var() when it reads the sheet.
No: the colour comes from the parent instead.
What does a broken var() give a property that does not pass down, such as background-color?Tap to reveal
- It starts from scratch.
Its initial value: transparent, for a background.
Did you know?
Why the earlier line does not come back
The surprise in this topic has a reason. A normal mistake in CSS fails early, while the browser reads the style sheet, so the bad line is dropped and the earlier line stays. A variable cannot be checked until the page is styled, and by then the browser has already thrown away the other values. The standard calls this invalid at computed-value time.
Why it fits here: It explains why this topic's earlier line does not come back when a variable is missing.
A fallback can hold commas
A fallback may contain commas of its own. The Custom Properties standard says everything between the first comma and the end of var() is the fallback, so var(--foo, red, blue) has the fallback red, blue. That lets a whole font list, such as Arial, sans-serif, stand as one fallback.
Why it fits here: It shows how much this topic's fallback can hold: a whole list, not only one value.
In one line
A fallback, as in var(--name, teal), gives a plan for a missing variable. With no value and no fallback, the property acts as if never set, taking its parent's value or its initial value, and an earlier declaration does not come back.
Sums in CSS: calc()
At a glance
A tailor measures a chest of 100 centimetres and adds 4 for ease. On a page the sums are harder, because one number may be a share of the screen and the other a fixed size: the full width, less 40 pixels. The calc() function asks the browser to do that sum as the page is drawn.
It can mix units such as % and px. Plus and minus need spaces around them, and one side of a * must be a plain number. Multiplying by 1px turns a plain number from a variable into a length.
Take a guess: Is calc(100% -40px) the same as calc(100% - 40px)?
A tailor measures a chest of 100 centimetres and adds 4 for ease of movement. On a page, the sums are harder, because the two numbers may be in different units, and one may not be known until the page is shown: "the full width, less 40 pixels". You cannot work that out in advance, because the full width depends on the screen. The browser can, and calc() asks it to.
A CSS function that does a sum with lengths, percentages and numbers, and gives the result as a value, using + and − with spaces around them, and * and /. The browser works it out as it draws the page, so it can mix units.
<!DOCTYPE html>
<style>
body { margin: 0; }
.main { width: calc(100% - 40px); height: 40px; background-color: gold; }
</style>
<div class="main">Today's offers</div>
Checked in Chrome
- at 800: 800 − 40 = 760
- at 375: 375 − 40 = 335; the same rule, a different answer
No fixed number could do this. The sum is redone at every width, leaving exactly 40 pixels, which is what a sidebar of 40 pixels needs.
The rules of the sum
| Sign | Example | Rule |
|---|---|---|
| + and − | calc(100% - 40px) | spaces on both sides are required |
| * | calc(8px * 3) | one side must be a plain number |
| / | calc(100% / 3) | the right side must be a plain number |
No spaces around the minus
Written calc(100%-40px), the browser reads -40px as a negative number with no sign between it and 100%. The whole line is dropped, and no error appears.
<!DOCTYPE html>
<style>
body { margin: 0; }
.main { width: calc(100%-40px); height: 40px; }
</style>
<div class="main">Today's offers</div>
Checked in Chrome
- (the slip: the width is dropped, and the box stays 800 wide)
calc() with variables
Together, variables and sums make a system: one base number, and every size built from it. A shop's sheet might have one unit of space, 8 pixels, with every gap a whole number of units. Then everything lines up, and changing the base changes the whole page in step.
<!DOCTYPE html>
<style>
:root { --unit: 8px; }
body { margin: 0; }
.small { padding: var(--unit); }
.medium { padding: calc(var(--unit) * 2); }
.large { padding: calc(var(--unit) * 3); }
</style>
<p class="small">Rice</p>
<p class="medium">Dal</p>
<p class="large">Atta</p>
Checked in Chrome
- one unit: 8px
- two units: 16px
- three units: 24px
Turning a number into a length
Here is the right way to do what var(--n)px could not. Keep the variable a plain number, then multiply it by one of the unit you want.
<!DOCTYPE html>
<style>
:root { --n: 3; }
body { margin: 0; }
.bar { width: calc(var(--n) * 10px); height: 20px; background-color: teal; }
</style>
<div class="bar"></div>
Checked in Chrome
- 3 × 10px = 30 pixels
A variable in one element's style
A variable can be set in an element's own style attribute. This suits numbers that belong to one element: the data, kept in the HTML, and the look, kept in the CSS.
<!DOCTYPE html>
<style>
body { margin: 0; }
.shop { display: grid; grid-template-columns: repeat(var(--columns), 1fr); }
</style>
<div class="shop" style="--columns: 4">
<div class="card">Rice</div><div class="card">Dal</div>
<div class="card">Atta</div><div class="card">Ghee</div>
</div>
Checked in Chrome
- the HTML says 4, and the grid makes 4 columns of 200
Inside min(), max() and clamp(), a sum needs no calc() of its own, as you saw with clamp(1.5rem, 1rem + 2vw, 2.5rem). They all do sums already.
Worked example 5
A results page shows three bars: Maths 92, Science 85 and English 74, each a percentage of the full width. The numbers should live in the HTML, and the CSS should work for any number. Write it and work out each bar's width in an 800 pixel window.
What we have: three marks out of 100, and a window 800 wide
What we need: one rule for all the bars, and each bar's width
The plan: put each mark in a --mark variable in its style attribute; the rule multiplies it by 1%
- Maths: 92% of 800 is 736.
- Science: 85% of 800 is 680.
- English: 74% of 800 is 592.
<!DOCTYPE html>
<style>
body { margin: 0; }
.bar { width: calc(var(--mark) * 1%); height: 20px; margin-bottom: 4px; background-color: teal; color: white; }
</style>
<div class="bar" style="--mark: 92">Maths</div>
<div class="bar" style="--mark: 85">Science</div>
<div class="bar" style="--mark: 74">English</div>
Checked in Chrome
- 736, 680 and 592 pixels at 800
- and they scale with the window: at 375, 345, 319 and 278
.bar { width: calc(var(--mark) * 1%); } with style="--mark: 92" on each bar: 736, 680 and 592 pixels at 800.
Check: the browser measured exactly those widths.
When you are stuck: calc()
A calc() that does nothing: are there spaces around + and −?
Multiplying two lengths: one side must be a plain number, so keep the variable a number.
Not sure what it came to: the Computed tab in DevTools shows the final number.
Your turn
What is calc(100% - 100px) in an 800 pixel wide parent?Tap to reveal
- A sum.
700 pixels.
Why is calc(100%-100px) dropped?Tap to reveal
- The signs need room.
There must be spaces around the minus.
How do you turn --n: 5 into 5 pixels?Tap to reveal
- Multiply by one of the unit.
calc(var(--n) * 1px).
Did you know?
The spaces around plus and minus
calc() is strict about spaces. The CSS Values standard requires whitespace on both sides of the + and - operators, though * and / may go without. The reason is the minus sign: in 50% -2px, the -2px reads as one negative number, not as minus 2px, so there is no sum to do.
Why it fits here: It is the rule behind this topic's warning that plus and minus need spaces around them.
CSS knows pi
calc() grew into a full calculator. The CSS Values standard now has trigonometric functions, sin(), cos(), tan() and their inverses, along with pow() and sqrt(), and two constants: e, and pi, the ratio of a circle's circumference to its diameter, about 3.14159. The two constants work only inside a calculation.
Why it fits here: These sit beside this topic's calc(), in the same family of math functions.
In one line
The calc() function does a sum as the page is drawn, so it can mix units such as % and px. Plus and minus need spaces around them, one side of * must be a plain number, and multiplying by 1px turns a number variable into a length.
A whole look in one place: themes
At a glance
A school has a summer uniform and a winter one: the children and the rules stay the same, and only the cloth changes. A theme does the same for a page. The rules stay, and a small set of variables named after roles, such as the background, the text and the accent, gets new values.
prefers-color-scheme follows the device's setting, and a data-theme attribute follows the visitor's own choice. The color-scheme property tells the browser to draw its own parts, such as scrollbars and form fields, to match. Contrast must be checked in every theme.
Take a guess: If a dark theme changes the background but not the text colour, what problem do readers meet?
A school has a summer uniform and a winter one. The children are the same, the rules for wearing it are the same, and only the cloth changes. A theme does the same for a page: the rules stay, and a small set of variables changes.
Name the roles, not the colours
The named values of a design are often called design tokens. For a theme, each should name a role on the page: the background, the text, the accent. Then a dark theme means giving those few names new values, and no other rule needs to change.
| Token | Its role | Light value | Dark value |
|---|---|---|---|
--bg | the page's background | white | rgb(17, 17, 17) |
--text | the words | rgb(34, 34, 34) | rgb(238, 238, 238) |
--accent | links and buttons | teal | turquoise |
Following the device: prefers-color-scheme
Phones and computers can be set to a dark appearance, often after sunset. The media feature prefers-color-scheme reads that setting, as prefers-reduced-motion read the other.
<!DOCTYPE html>
<style>
:root { --bg: white; --text: rgb(34, 34, 34); }
@media (prefers-color-scheme: dark) {
:root { --bg: rgb(17, 17, 17); --text: rgb(238, 238, 238); }
}
body { margin: 0; background-color: var(--bg); color: var(--text); }
</style>
<p>Fresh vegetables, delivered in Pune.</p>
Checked in Chrome
- on a light device: white, with dark text
- on a dark device: near-black, with pale text; the same rules, two new values
The rules for body never mention a colour. They ask for roles, and the query changes what the roles mean. The dark values are not pure black and white, on purpose: pure white text on pure black glares, and many readers find it tiring.
A switch on the page: data-theme
Some visitors want to choose for themselves. A switch on the page can set an attribute on the <html> element, and the sheet answers to it. Setting it needs a little JavaScript, which comes in a later step; here the attribute is written in the HTML.
<!DOCTYPE html>
<html data-theme="dark">
<style>
:root { --bg: white; }
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) { --bg: rgb(17, 17, 17); }
}
:root[data-theme="dark"] { --bg: rgb(17, 17, 17); }
body { margin: 0; background-color: var(--bg); }
</style>
<p>Fresh vegetables</p>
Checked in Chrome
- on a light device, the visitor chose dark, and the attribute wins
<!DOCTYPE html>
<html data-theme="light">
<style>
:root { --bg: white; }
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) { --bg: rgb(17, 17, 17); }
}
:root[data-theme="dark"] { --bg: rgb(17, 17, 17); }
body { margin: 0; background-color: var(--bg); }
</style>
<p>Fresh vegetables</p>
Checked in Chrome
- on a dark device, the visitor chose light, and the :not() keeps the dark values away
Read the sheet slowly. The dark device's rule has :root:not([data-theme="light"]): "the root, unless the visitor chose light". The next rule says: "the root, when the visitor chose dark". Together they give the visitor's choice the last word, and the device's setting the first.
Telling the browser: color-scheme
Your variables dress your own boxes. The browser also draws things of its own: form controls, scrollbars, the blank page before the sheet arrives. color-scheme: light dark tells it that this page handles both, so it draws its own pieces to match. A newer function, light-dark(), then gives a pair of values in one place: the first for light, the second for dark.
<!DOCTYPE html>
<style>
:root { color-scheme: light dark; --bg: light-dark(white, rgb(17, 17, 17)); }
body { margin: 0; background-color: var(--bg); }
</style>
<input value="Rice">
Checked in Chrome
- the first value, on a light device
- the second value, on a dark device
- on a dark device: and the input box, drawn by the browser, follows too
Colours made from colours: color-mix()
A hover shade or a pale background can be made from the accent itself, so that it follows every change. color-mix(in srgb, var(--accent) 50%, white) mixes half the accent with half white, as you would mix paint.
<!DOCTYPE html>
<style>
:root { --accent: teal; }
body { margin: 0; }
.tag { background-color: color-mix(in srgb, var(--accent) 50%, white); }
</style>
<span class="tag">New</span>
Checked in Chrome
- red is halfway from 0 to 1, and green and blue halfway from 0.5 to 1
Check the contrast in both themes
An accent that passes on white may fail on black. The 4.5 to 1 rule from the colours lesson still applies, and it must be checked in each theme.
| Text colour | On | Contrast | For body text |
|---|---|---|---|
| teal | white | 4.8 to 1 | passes |
| teal | rgb(17, 17, 17) | 4.0 to 1 | fails |
| turquoise | rgb(17, 17, 17) | 11.5 to 1 | passes |
This is why a theme changes the accent as well. Turquoise here is the lighter partner of teal, rgb(64, 224, 208).
A memory aid
Change the cloth, not the pattern. Rules ask for roles; a theme gives the roles new values.
Worked example 6
A shop's page has a background, text and a link colour, all written as plain colours in many rules, in teal and black on white. Build a dark theme that follows the device, and say why the link colour must change too.
What we have: three roles, and the light values white, rgb(34, 34, 34) and teal
What we need: tokens for the roles, dark values, and rules that ask for the tokens
The plan: name the roles --bg, --text and --accent on :root; set new values inside prefers-color-scheme: dark; every rule asks for a role
- The rules now say
var(--bg),var(--text)andvar(--accent), and never name a colour. - The dark values: rgb(17, 17, 17), rgb(238, 238, 238) and turquoise.
- The link must change: teal on the dark background has a contrast of only 4.0 to 1, below 4.5; turquoise has 11.5 to 1.
<!DOCTYPE html>
<style>
:root { --bg: white; --text: rgb(34, 34, 34); --accent: teal; }
@media (prefers-color-scheme: dark) {
:root { --bg: rgb(17, 17, 17); --text: rgb(238, 238, 238); --accent: rgb(64, 224, 208); }
}
body { margin: 0; background-color: var(--bg); color: var(--text); }
a { color: var(--accent); }
</style>
<p>Fresh vegetables</p>
<a href="#offers">Today's offers</a>
Checked in Chrome
- on a light device: a teal link
- on a dark device: a near-black page
- on a dark device: pale text
- on a dark device: and a turquoise link
:root { --bg: white; --text: rgb(34, 34, 34); --accent: teal; } and, inside @media (prefers-color-scheme: dark), the three dark values. Teal must go, because it reaches only 4.0 to 1 on the dark background.
Check: the browser drew each value in its window, and the contrast figures were worked out from the colours.
When you are stuck: themes
Part of the page stays light in the dark theme: look for a colour written out in a rule, and make it ask for a role.
To test without changing your settings: in DevTools, press Ctrl+Shift+P, type "dark", and emulate the colour scheme.
Form boxes stay white: add color-scheme: light dark.
Your turn
Which media feature reads whether a device is set to dark?Tap to reveal
- It starts with prefers.
prefers-color-scheme.
Why is --bg a better token than --white?Tap to reveal
- In a dark theme?
It names the role; in a dark theme it is not white.
What does color-scheme: light dark tell the browser?Tap to reveal
- Its own pieces.
That the page handles both, so it should draw its own controls to match.
Did you know?
color-scheme dresses the browser's own parts
Variables can repaint your own parts of a page, but not the browser's. The color-scheme property tells the browser which colour schemes a page is designed for. Matched with the reader's preference, it settles the used colour scheme, which affects the browser's own colours, such as those of form controls and scrollbars.
Why it fits here: It finishes this topic's themes: your variables dress the page, and color-scheme dresses the browser's parts.
light-dark() picks the colour for you
A newer function can replace a pair of theme values. CSS Color Level 5 defines light-dark(): given two colours, it gives the first when the element's colour scheme is light and the second when it is dark. So color: light-dark(black, white) follows the theme with no media query at all.
Why it fits here: It does in one function what this topic's themes do with role variables and a query.
Source: W3C: CSS Color Level 5
In one line
A theme is a small set of role variables given new values: prefers-color-scheme follows the device, a data-theme attribute follows the visitor's choice, color-scheme tells the browser, and contrast must be checked in each theme.
Where it is used
Almost every large site today keeps its look in variables. These are the uses you will meet most.
| What you learned | Where it is used | A real example |
|---|---|---|
| tokens on :root | the design of a whole site | a bank's colours, spaces and corners in one short list |
| overriding in a section | parts of a page with their own look | a festival section in a shop's usual page |
| variables in components | buttons, cards and alerts | a danger button that only sets one variable |
| var() with a fallback | components shared between sites | a date picker that any site can dress |
| calc() | layouts that mix units | a main area that is the full width less a fixed sidebar |
| a unit of space | spacing that lines up | every gap a whole number of 8 pixel units |
| inline variables | data shown as sizes | bars of a results chart, each with its own mark |
| prefers-color-scheme | dark themes | a reading app that turns dark after sunset |
Mistakes and debugging
These are the slips everyone makes with variables, each measured in the browser.
1. A name that does not match
--Brand and --brand are two variables, and a misspelt name gives no error. The fix: copy the name; do not retype it.
2. Forgetting var()
<!DOCTYPE html>
<style>
:root { --brand: teal; }
h1 { color: --brand; }
</style>
<h1>Asha Stores</h1>
Checked in Chrome
- (the slip: color: --brand is not a colour, so the line is dropped)
The fix: color: var(--brand). Two dashes set a variable; var() reads one.
3. Setting it on a neighbour
A variable passes down, never sideways. The fix: set it on a shared parent, or on :root.
4. Expecting a fallback from an earlier line
After color: red; color: var(--nope); the red does not come back. The fix: put the fallback inside: var(--nope, red).
5. Gluing on a unit
var(--n)px is dropped. The fix: calc(var(--n) * 1px).
6. No spaces around + or −
calc(100%-40px) is dropped. The fix: calc(100% - 40px).
7. A variable in a media query's condition
<!DOCTYPE html>
<style>
:root { --wide: 600px; }
p { color: black; }
@media (min-width: var(--wide)) {
p { color: red; }
}
</style>
<p>Rice</p>
Checked in Chrome
- (the slip: at 800, wider than 600, the rule still does not apply, because the condition cannot read a variable)
The fix: write the number in the condition.
8. A name that is its own value
--teal: indigo; is the sad end of naming by look. The fix: name the job: --accent.
9. A theme with leftovers
One rule with color: black written out disappears on the dark background. The fix: every colour in every rule asks for a role.
The debugging corner: following a variable
In DevTools' Styles panel, hold the pointer over any var() to see its value, and click it to jump to the rule that set it. A variable with no value is marked. Change a variable on :root in the Styles panel and watch the whole page change at once: it is the quickest way to try out a new colour.
Quick card
The lesson on one card.
Every idea of the lesson
<!DOCTYPE html>
<style>
:root { --bg: white; --text: rgb(34, 34, 34); --accent: teal; --unit: 8px; }
@media (prefers-color-scheme: dark) {
:root { --bg: rgb(17, 17, 17); --text: rgb(238, 238, 238); --accent: rgb(64, 224, 208); }
}
body { margin: 0; background-color: var(--bg); color: var(--text); }
.sale { --accent: crimson; }
h2 { color: var(--accent); }
.main { width: calc(100% - 40px); padding: calc(var(--unit) * 2); box-sizing: border-box; }
.bar { width: calc(var(--mark) * 1%); height: 10px; background-color: var(--accent, teal); }
.tag { color: var(--nothing, teal); }
</style>
<div class="main">
<h2 class="plain">Daily needs</h2>
<div class="sale"><h2 class="off">Diwali sale</h2></div>
<div class="bar" style="--mark: 50"></div>
<span class="tag">New</span>
</div>
Checked in Chrome
- the accent, from :root
- overridden for the sale
- calc() gives 760 wide, and two units of padding
- 50% of the 728 inside the padding, from a number in the HTML
- and the fallback covers the missing variable
- on a dark device, the page is near-black
- on a dark device: and the accent changes, by one set of values
| Tool | Write it as | It means |
|---|---|---|
| set | :root { --accent: teal; } | a name for a value, for the whole page |
| read | var(--accent) | the value of accent |
| fallback | var(--accent, teal) | or teal, if there is none |
| override | .sale { --accent: crimson; } | a new value, for everything inside .sale |
| sums | calc(100% - 40px) | mixed units, spaces around the minus |
| build sizes | calc(var(--unit) * 3) | three units of space |
| number to length | calc(var(--n) * 1px) | never var(--n)px |
| inline | style="--mark: 92" | a value for one element |
| dark device | @media (prefers-color-scheme: dark) | rules for a dark setting |
| visitor's choice | :root[data-theme="dark"] | answers to an attribute |
| browser's pieces | color-scheme: light dark | its own controls match |
| mixing | color-mix(in srgb, var(--accent) 50%, white) | a tint of the accent |
And that is the whole cloth of CSS: selectors, colours, boxes, type, flexbox, grid, positioning, responsive pages, motion, and now variables that keep it all in one place.
The story: One vat
You give the Fair's colour a name, once, at the top of the sheet, and every button, border and heading now asks for it by that name. When the council changes its mind again, one line changes, and the whole board turns saffron in a single stroke.
At sunset the great glass darkens and the board follows, each colour swapped for its night-time partner.
Meher runs a finger along the last seam and, for once, finds nothing to measure. "The Tailors have no more to teach you," she says. "Go and see what the Lens-grinders can show you."
Reagents gathered: --name, var(), :root, fallback, calc(), prefers-color-scheme.
Sources
- MDN Web Docs (Prose CC BY-SA 2.5 or later; code samples added since 2010-08-20 CC0 (its licensing page, read 2026-10-26); reused with credit)
- HTML Living Standard (WHATWG) (CC BY 4.0: "Copyright WHATWG (Apple, Google, Mozilla, Microsoft). This work is licensed under a Creative Commons Attribution 4.0 International License" (its acknowledgements page, read 2026-10-26); reused with credit)