CSS Variables & Custom Properties

Learn CSS custom properties — define, inherit, override, and dynamically update variables for theming.

Category: Web Development · v1.0.0
Step 1 of 6

Step 1: What are CSS Variables?

CSS Custom Properties (commonly called CSS variables) let you store values in one place and reuse them throughout your stylesheet. They make your CSS more maintainable, readable, and dynamic.

A custom property is declared with a double-hyphen prefix (--) and accessed with the var() function:

:root {
  --primary-color: #3b82f6;
  --font-size: 16px;
  --spacing: 1rem;
}

.button {
  background: var(--primary-color);
  font-size: var(--font-size);
  padding: var(--spacing);
}

You can also provide a fallback value in case the variable is not defined:

color: var(--accent-color, #e74c3c);

Key terms:

  • Custom property — a property name starting with --, e.g. --my-color
  • var() — the function used to retrieve a custom property's value
  • :root — the top-level selector (the <html> element), used for global variables
  • Fallback value — a default passed as the second argument to var()
  • Scope — variables are inherited by descendant elements and can be overridden at any level

About This Lab

CSS Custom Properties (variables) revolutionize how we write maintainable stylesheets. In this lab, you'll learn to declare and use variables, understand scope and inheritance, override values in nested selectors, build a dynamic theme switcher, calculate values with var() and calc(), and create responsive designs with fewer lines of code.

How It Works

  1. Read each step's explanation of CSS variable concepts
  2. Modify variables and see styles update instantly
  3. Build a theme switcher from scratch
  4. Experiment with scope and inheritance
  5. Complete the quiz to test your understanding