CSS Advanced: Variables, Motion and Modern CSS
CSS Custom Properties (Variables)
In this lesson you will
- Declare and use CSS custom properties
- Explain scope and fallback values
- Build a theme that can be switched
Introduction
Imagine your brand colour appears in 40 places. A designer asks you to change it. Without variables you search and replace 40 times and hope you miss nothing. CSS custom properties, often called CSS variables, let you store the value once and use it everywhere.
The simple explanation
A custom property is a named value you can reuse.
You declare it with two dashes at the start of the name, and use it with var().
Change --brand to tomato and run it again: both elements update.
:root is the top of the document, so variables declared there are available everywhere.
Quick quiz
How do you use a custom property named --brand?
Scope: override locally
Custom properties follow the cascade and inheritance. A variable set on one element applies to that element and its children, so you can override it for just one area.
The .panel rule is written once. The .dark class only changes the variables.
Fallback values
var() accepts a second value to use if the variable is missing.
HTML
color: var(--accent, hotpink);Themes and JavaScript
Because variables change many properties at once, they are ideal for themes such as dark mode. JavaScript can change them too:
Quick quiz
Why are custom properties good for dark mode?
Try it yourself
Add --space: 16px to :root and use it for the padding of .box and the margin-bottom. Then change it to 32px.
Summary
- Declare with
--name: value;and use withvar(--name). - Declare shared values on
:root, and override them locally. var(--x, fallback)gives a default.- JavaScript can change variables with
style.setProperty.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading