CSS Snippet

Dark Mode with CSS Variables

Difficulty: Medium

Implementing dark mode without a heavy theming library comes down to a stable token contract and a media query. This snippet covers the system-preference dark mode using `prefers-color-scheme`, a class-based override that lets users opt in or out, and a per-component theme that nests tokens for a single section.

Code Snippets
/

Dark Mode with CSS Variables

Dark Mode with CSS Variables

Implementing dark mode without a heavy theming library comes down to a stable token contract and a media query. This snippet covers the system-preference dark mode using `prefers-color-scheme`, a class-based override that lets users opt in or out, and a per-component theme that nests tokens for a single section.

CSS
Medium
3 snippets
css-selectors
css-variables
css-media-queries
code-template

580 views

9

Defining tokens (--bg, --fg, --accent) at :root gives every consumer a single source of truth. The prefers-color-scheme: dark media query overrides the same variables when the OS prefers dark, which automatically themes every element that references them. This is the lowest-overhead path to a respectful dark mode, since it follows the user's existing preference without any UI. The accent stays the same hue but lightens for dark mode so it keeps passing contrast on the new background.