Dark Mode in Tailwind: Light, Dark, and System
Three display modes the browser remembers, with no flicker when the page loads.
C Codesakura 1 min 0 comments
Contents
Visitors increasingly expect to choose between a light and a dark look themselves. This tutorial builds three options: light, dark, and follow the device setting.
Enabling the dark variant
In Tailwind 4, the dark: variant can be tied to a class on the html element:
@import 'tailwindcss';
@custom-variant dark (&:where(.dark, .dark *));Saving the visitor's choice
The choice is stored in localStorage, then the dark class is applied to match it.
const mode = localStorage.getItem('mode') || 'system'
const dark = mode === 'dark' || (mode === 'system' && matchMedia('(prefers-color-scheme: dark)').matches)
document.documentElement.classList.toggle('dark', dark)Preventing the flicker
Place the script above as a small inline script inside <head>, before the CSS loads. That way the page shows up in the right mode from the very first paint.
0 comments
Log in to join the conversation. Log in