CodeBlanks Logo Icon CodeBlanks

What are CSS variables?

CSS course · Intermediate · Lesson 70/98

Learn the custom property (--name) concept.

What is a CSS variable?

A CSS variable (custom property) lets you store a value by name and reuse it. The name starts with two dashes: --color, --space, --size. After it is defined, you call it with var(--color).

Variables are CSS's own storage: write the brand color in one place, read it in ten. When the value changes, you only update the definition; every match updates automatically.

Why use variables?

Writing the same color or spacing in ten places is tiring and error-prone. Use var(--color) instead of #2563eb; when the brand color changes, you only update a single line in :root.

The result: consistent look, fewer mistakes, faster changes. Teammates also see at a glance which color is the brand color.

Design token

A design token is the smallest reusable unit of a brand: the brand color, spacing size, corner radius, shadow tone. You define these as variables and use them across the whole page for a consistent interface.

For example, --color-brand, --space-medium, --corner-radius are tokens. When a designer updates one token, the whole interface changes at once; the developer never needs to touch the styles.

Exercise Define your first variable

Inside the :root selector, define a variable named --bg with the value #0f172a.

Show example solution
open a :root selector and write --bg: #0f172a; inside.
Example solution:
:root {
  --bg: #0f172a;
}

Test yourself

  1. Which is a valid CSS variable name?

    • --color
    • color
    • $color
    • @color
    Show answer

    --color — Correct. CSS variables start with two dashes: --color.

  2. Match the concepts

    --color
    custom property name
    var(--color)
    variable usage
    design token
    reusable value
    :root
    global scope
  3. Write a valid variable name

    :root {
      ____: #2563eb;
    }
    Show answer
    :root {
      --blue: #2563eb;
    }

All lessons in Intermediate