NelsonLabs
CSS Styling/CSS Variables

CSS Variables

CSS custom properties (variables) are one of the most powerful modern CSS features. They let you define values once and reuse them everywhere โ€” the foundation of any maintainable design system.

Defining and using CSS variables
css
/* Define variables on :root to make them globally available */
:root {
  --color-bg:      #0F0D0A;
  --color-surface: #201D15;
  --color-border:  #2E2A22;
  --color-text:    #EDE8DC;
  --color-muted:   #998870;
  --color-accent:  #C96A30;

  --font-sans: -apple-system, system-ui, sans-serif;
  --font-mono: "JetBrains Mono", monospace;

  --radius:  6px;
  --shadow:  0 4px 24px rgba(0, 0, 0, 0.4);

  --spacing-sm: 0.5rem;
  --spacing-md: 1rem;
  --spacing-lg: 2rem;
}

/* Use them with var() */
body {
  background: var(--color-bg);
  color: var(--color-text);
  font-family: var(--font-sans);
}

.card {
  background: var(--color-surface);
  border: 1px solid var(--color-border);
  border-radius: var(--radius);
  padding: var(--spacing-lg);
  box-shadow: var(--shadow);
}

.btn-primary {
  background: var(--color-accent);
  border-radius: var(--radius);
}

Dynamic theming โ€” dark/light mode

Switching themes with CSS variables
css
/* Default: dark theme */
:root {
  --bg:   #0F0D0A;
  --text: #EDE8DC;
}

/* Light theme when user prefers it */
@media (prefers-color-scheme: light) {
  :root {
    --bg:   #FAFAF7;
    --text: #1A1814;
  }
}

/* Or toggle with a class on <html> */
html.light {
  --bg:   #FAFAF7;
  --text: #1A1814;
}

body {
  background: var(--bg);
  color: var(--text);
  /* Automatically correct in both themes */ }

NOTE

Variables can be overridden locally. CSS variables follow the cascade. You can define a variable on :root as the default, then override it on a specific component. .dark-card { --bg: #000; } overrides --bg only inside that component โ€” without affecting the rest of the page.