Stop 04 · CSS FundamentalsTopics · 9/9

CSS Variables

Part of the Web Development Roadmap

In short

Your brand pink appears 40 times in the CSS. The client wants it a bit darker. With CSS variables, that's a one-line change instead of a find-and-replace nightmare.

CSS custom properties like --primary store values you can reuse across a stylesheet and change in one place, which makes themes like dark mode easy.

The jaadu mascot in a paint shop holds a pink swatch while a mixing machine fills a bucket with matching paint.

Think of it like this

The paint shop's colour code

When you repaint your room, you don't describe the shade every time. You tell the shop 'code 7342' and they mix it. CSS variables are those codes: define --brand once, use var(--brand) everywhere, change it in one place.

Watch it happen

How a variable flows down the page

:root --brand
body
header
.btn
main
.btn.ghost

1/4:root sets --brand: #ec4899. Every element on the page inherits it.

The big ideas

What you need to know

Define with --

Custom properties start with two dashes, like --brand: #ec4899. You read them with var(--brand).

They inherit

Define them on :root for the whole site, or on one component to change values just inside it.

Themes become easy

Swap the variable values for dark mode, and every element using them updates instantly.

Live in the browser

Unlike Sass variables, CSS variables exist at runtime. JavaScript can read and change them.

See it in code

Walk through the code

css
1:root {2  --brand: #ec4899;3  --text: #1f2937;4  --bg: #ffffff;5  --radius: 12px;6}7 8@media (prefers-color-scheme: dark) {9  :root { --text: #f3f4f6; --bg: #111827; }10}11body { color: var(--text); background: var(--bg); }12.btn {13  background: var(--brand);14  border-radius: var(--radius);15}16.btn.ghost { --brand: transparent; }   /* local override */

1/4Define your design tokens once on :root.

Dark mode is just new values for the same variables. The .ghost button changes --brand only inside itself.

Save yourself the pain

Common mistakes

Oops

Naming variables by colour, like --pink.

Do this instead

Name them by job, like --brand or --danger. Then a colour change doesn't make the name wrong.

Oops

Forgetting a fallback when a variable might be missing.

Do this instead

Use var(--gap, 1rem) so there's a default value.

Your mission

Add a theme switcher

~25 min

Quick check

What's one thing CSS variables can do that Sass variables can't?

Go deeper

  1. 1Move all your colours and spacing values into variables on :root.
  2. 2Build a simple dark mode by overriding the variables inside a class.
  3. 3Change a variable live in DevTools and watch the whole page update.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge