CSS Custom Properties

Introduction

CSS Custom Properties (AKA CSS Variables) allow dynamic, reusable, themeable styling. They are the backbone of modern design systems and dark mode implementations. This tutorial goes deeper into advanced usage beyond basics.

1. Root Theme Setup

:root {
  --bg: #121212;
  --text: #e0e0e0;
  --accent: #64b5f6;
  --radius: 10px;
}
    

2. Component-Level Overrides

.card {
  --radius: 20px;
  border-radius: var(--radius);
  background: #1e1e1e;
  padding: 20px;
}
    

3. Nested Variables

.container {
  --pad: 20px;
}

.item {
  padding: var(--pad);
}
    

4. Dynamic Theme Switching (JS)

function setAccent(color) {
  document.documentElement.style
    .setProperty("--accent", color);
}

setAccent("#00ff99");
    

5. Using Variables in Animations

:root {
  --spin: 3s;
}

.spinner {
  animation: spin var(--spin) linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}
    

6. Using Variables in Media Queries

:root {
  --font-size: 18px;
}

@media (max-width: 600px) {
  :root {
    --font-size: 14px;
  }
}

p { font-size: var(--font-size); }
    

7. Complex Calculations

:root {
  --base: 10px;
}

.box {
  padding: calc(var(--base) * 3);
}
    

8. Variable-Based Gradients

:root {
  --start: #64b5f6;
  --end: #90caf9;
}

.button {
  background: linear-gradient(var(--start), var(--end));
}
    

9. Fallbacks for Missing Variables

color: var(--brand, #fff);
    

10. Local Theming for Components

.alert {
  --alert-bg: #222;
  --alert-text: #f00;

  background: var(--alert-bg);
  color: var(--alert-text);
}
    

11. Reusable Spacing System

:root {
  --space-1: 4px;
  --space-2: 8px;
  --space-3: 16px;
  --space-4: 24px;
}

div { margin-bottom: var(--space-3); }
    

12. Theme Packs

body.light {
  --bg: #ffffff;
  --text: #000000;
  --accent: #64b5f6;
}

body.dark {
  --bg: #121212;
  --text: #e0e0e0;
  --accent: #90caf9;
}
    

13. Summary