CSS Variables
A CSS variable, also called a custom property, stores a value under a name. var() reads the value wherever the name is used.
Store a colour and read it
The :root rule stores a green under the name --main. The heading rule reads the name and paints the stored green.
:root {
--main: #2e7d32;
}
h1 {
color: var(--main);
}One variable, three elements
The same name feeds the heading colour, the box border and the button background. Each rule reads the one stored value.
:root {
--main: #2e7d32;
}
h1 {
color: var(--main);
}
.box {
border: 2px solid var(--main);
}
button {
background-color: var(--main);
}Override a variable locally
The box stores navy under the same name. Text inside the box reads the local value, and the heading keeps the root value.
:root {
--main: #2e7d32;
}
h1 {
color: var(--main);
}
.box {
--main: navy;
}
.box p {
color: var(--main);
}Example
:root {
--main: #2e7d32;
--soft: #e8f5e9;
}
h1 {
color: var(--main);
}
.box {
background-color: var(--soft);
border: 2px solid var(--main);
}
button {
background-color: var(--main);
color: white;
}Key points
- A custom property name starts with two dashes, like --main
- Custom property names are case-sensitive
- The :root selector matches the page root, so values set there reach every element
- var() accepts a fallback value, as in var(--main, red)
- Custom properties inherit like other inherited properties
- One changed value updates every rule that reads it
In this example, the :root rule stores two colours under two names. The heading reads --main for its text colour. The box reads --soft for its background and --main for its border. The button reads --main for its background and uses white text.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What happens when the value of --main changes on :root?