Dark Mode Strategies
Compare the media strategy (prefers-color-scheme) and the class strategy (toggling a dark class on html) and when to use each.
Why Dark Mode Matters
Dark mode has become a first-class feature expectation in modern web apps. Users prefer it for reducing eye strain in low-light environments, and it can extend battery life on OLED screens. Tailwind CSS makes implementing dark mode straightforward with a built-in dark variant. Before writing a single class, you need to choose between two strategies: the media strategy and the class strategy.
The Media Strategy Explained
The media strategy relies on the browser's prefers-color-scheme CSS media query. When the user sets their operating system to dark mode, Tailwind automatically activates all dark: prefixed utilities. This requires zero JavaScript — the browser handles everything. It is the simplest approach but offers no user toggle within your app itself.
/* Tailwind uses this media query under the hood */
@media (prefers-color-scheme: dark) {
/* dark: utilities are applied here */
}