0PricingLogin
React Academy · Lesson

CSS Variables for Theme Switching

Define a complete color palette with CSS custom properties and switch themes by toggling a data attribute.

Defining Color Tokens on :root

CSS custom properties (variables) defined on :root are globally available throughout the stylesheet. You define a complete color palette once — backgrounds, text colors, surfaces, borders — and reference them everywhere. This single source of truth makes theme switching trivial.

Dark Theme Overrides with data-theme

When a data-theme="dark" attribute is set on document.documentElement, a CSS selector like [data-theme='dark'] overrides the root variables with dark values. Components reference var(--color-bg) and automatically pick up the new values without any code changes.

All lessons in this course

  1. Detecting System Color Scheme
  2. CSS Variables for Theme Switching
  3. React Context for Theme State
  4. Persisting Theme and Preventing Flash
← Back to React Academy