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
- Detecting System Color Scheme
- CSS Variables for Theme Switching
- React Context for Theme State
- Persisting Theme and Preventing Flash