CSS Custom Properties (Variables)

🎨 CSS Architecture Lesson 14 Advanced

CSS Custom Properties (also called CSS Variables) store reusable values in the stylesheet itself. They are live in the browser, can be updated at runtime with JavaScript, and are the foundation of modern design systems and theme switching.

1 Defining & Using Variables
CSS — Design System Tokens
/* Define on :root for global scope */
:root {
  /* Color palette */
  --clr-primary-400: #6366f1;
  --clr-primary-600: #4f46e5;
  --clr-surface:     #0f172a;
  --clr-text:        #f1f5f9;
  --clr-text-muted:  #94a3b8;

  /* Spacing scale */
  --space-xs: 4px;
  --space-sm: 8px;
  --space-md: 16px;
  --space-lg: 24px;
  --space-xl: 40px;

  /* Typography */
  --font-sans: 'Inter', system-ui, sans-serif;
  --text-base: 1rem;
  --text-lg:   1.125rem;

  /* Borders */
  --radius-sm: 4px;
  --radius-md: 8px;
  --radius-full: 9999px;

  /* Shadows */
  --shadow-md: 0 4px 12px rgba(0,0,0,0.3);
}

/* Usage */
.btn {
  background: var(--clr-primary-400);
  padding: var(--space-sm) var(--space-md);
  border-radius: var(--radius-md);
  font-family: var(--font-sans);
  box-shadow: var(--shadow-md);
}
2 Dark / Light Theme Switching
CSS + JS — Theme Switch
:root { --bg: #ffffff; --text: #0f172a; }
[data-theme="dark"] { --bg: #0f172a; --text: #f1f5f9; }

body { background: var(--bg); color: var(--text); transition: background 0.3s, color 0.3s; }
JavaScript — Toggle Theme
document.documentElement.dataset.theme =
  document.documentElement.dataset.theme === 'dark' ? '' : 'dark';
3 Code Challenge
Challenge: Build a full design system :root block with at least 10 tokens (colors, spacing, radius). Implement a working light/dark theme toggle using data-theme attribute switching.