Lesson 24 / 28
CSS Custom Properties (Variables)
Reusable values defined once and referenced everywhere.
--name and var()
Declare a custom property with --name: value; and read it anywhere with var(--name). They cascade and inherit like any other property.
A tiny theme
Change --brand-color once and every reference updates.
:root {
--brand-color: #264de4;
--spacing: 16px;
}
.button {
background-color: var(--brand-color);
padding: var(--spacing);
}
.link {
color: var(--brand-color);
}Scoping variables
Define global variables on :root; override them locally on any selector to theme just that section — like a .dark-mode class redefining --bg-color.
Quick check: How do you read the value of a CSS custom property named --gap?
- gap(--gap)
- var(--gap)
- $gap
Answer
var(--gap) — The var() function reads a custom property's current value.