<htmlstart/>

CSS Variables

Custom properties let you reuse values and build a design system.

Defining Variables

Declare variables on :root to make them global. Names must start with --.

:root {
  /* Colors */
  --color-primary:   #D62828;
  --color-bg:        #F5F3EE;
  --color-text:      #111111;
  --color-muted:     #767370;

  /* Spacing */
  --space-sm:  8px;
  --space-md:  16px;
  --space-lg:  32px;
  --space-xl:  64px;

  /* Typography */
  --font-sans: "Inter", system-ui, sans-serif;
  --font-mono: "Space Mono", monospace;
  --radius:    4px;
}

Using Variables

button {
  background: var(--color-primary);
  color: var(--color-bg);
  padding: var(--space-sm) var(--space-md);
  border-radius: var(--radius);
  font-family: var(--font-sans);
}

/* Fallback value if variable not defined */
.card {
  border: 1px solid var(--color-border, #ccc);
}

Dark Mode with Variables

:root {
  --bg: #ffffff;
  --text: #111111;
}

@media (prefers-color-scheme: dark) {
  :root {
    --bg: #111111;
    --text: #f4f4f4;
  }
}

body {
  background: var(--bg);
  color: var(--text);
}
CSS variables are live — change them with JavaScript (el.style.setProperty("--color", "red")) to build theme switchers, dynamic UI, and more.
🧩

Test Yourself

4 questions
Q1.How do you declare a CSS custom property (variable)?
Q2.How do you USE a CSS variable in a declaration?
Q3.Where should global CSS variables be declared?
Q4.How do you provide a fallback value in var()?