CSS - Variables (Custom Properties)

Overview

Estimated time: 15–18 minutes

CSS variables enable theming and dynamic composition with the power of the cascade.

Learning Objectives

  • Declare and consume custom properties.
  • Override variables in scopes (e.g., dark mode).

Details & Examples

:root{ --brand: #22c55e; --radius: .5rem; }
.button{ background: var(--brand); border-radius: var(--radius); }
.dark{ --brand: #16a34a; }

Try it

Pitfalls

  • Variables are resolved at computed-value time; not all contexts support them (e.g., media queries).

Checks for Understanding

  1. Where do you declare global variables?
Show answers
  1. In :root or appropriate container scope.

Exercises

  1. Create a theme with --brand, --surface, and --radius variables; demonstrate an alternate theme by overriding at a container.
  2. Refactor a button component to use variables and verify it adapts in both light and dark modes.