CPCODELAB
CSS

CSS Custom Properties (Variables)

9 min read

Defining and Using CSS Variables

CSS custom properties (commonly called CSS variables) let you store values under a name that starts with --. You then reference them with var(). They cascade and inherit just like regular properties, which makes them far more powerful than preprocessor variables.

css
:root {
  /* Design tokens */
  --color-primary:   #6366f1;
  --color-primary-d: #4f46e5;
  --color-text:      #1a1a2e;
  --color-muted:     #64748b;
  --color-surface:   #ffffff;
  --color-border:    #e2e8f0;

  --radius-sm: 4px;
  --radius-md: 8px;
  --radius-lg: 16px;

  --shadow-sm: 0 1px 3px rgba(0,0,0,0.12);
  --shadow-md: 0 4px 12px rgba(0,0,0,0.10);

  --font-body: 'Inter', system-ui, sans-serif;
  --font-mono: 'JetBrains Mono', monospace;
}

.button {
  background: var(--color-primary);
  border-radius: var(--radius-md);
  box-shadow: var(--shadow-sm);
  font-family: var(--font-body);
}

.button:hover {
  background: var(--color-primary-d);
}

/* Fallback value when a variable might not be defined */
.card {
  color: var(--card-text, var(--color-text));
}

Dark Mode with Custom Properties

css
:root {
  --bg: #ffffff;
  --text: #1a1a2e;
}

@media (prefers-color-scheme: dark) {
  :root {
    --bg: #0f0f1a;
    --text: #e2e8f0;
  }
}

body {
  background: var(--bg);
  color: var(--text);
}

CSS custom properties are the foundation of any modern design system. If you are learning CSS through a structured program like CPCODELAB, you will build an entire token system on top of these.

Ready to test yourself?
Practice CSS— quiz & coding exercises