Language 8 of 10 · Topic 0.5

CSS Custom Properties (Variables) & Theme Switching

1Concept

CSS Variables (--primary-color) cascade down the DOM and can be dynamically manipulated in JavaScript for dark/light theme switching.

2Architecture Diagram

:root { --bg: #ffffff; }
[data-theme="dark"] { --bg: #0f172a; }

3Code Example

Stage 0 Language Foundations
:root {
    --bg-surface: #ffffff;
    --text-primary: #0f172a;
    --accent: #6366f1;
}

[data-theme="dark"] {
    --bg-surface: #0f172a;
    --text-primary: #f8fafc;
    --accent: #818cf8;
}

.container {
    background-color: var(--bg-surface);
    color: var(--text-primary);
    border: 1px solid var(--accent);
}

4Expected Output

[Instant dark/light theme switching without page reload]

5Key Takeaways

  • CSS custom properties update instantly across all consuming elements.
  • Variables cascade down the DOM hierarchy.
  • Supports fallback values: var(--custom, #000000).