Skip to main content
EZ

Dark mode implementation with Tailwind CSS - complete guide

Emily Zhang General Discussion 148 views
Just spent a weekend implementing a proper dark mode toggle for my portfolio site. Here is what I learned: The simple approach uses Tailwind dark: variant like bg-white dark:bg-gray-900. The tricky parts: 1. System preference detection using prefers-color-scheme media query 2. User preference persistence by storing the choice in localStorage 3. Flash prevention by adding a script in the head tag before body renders 4. Transition smoothness by adding transition-colors duration-200 to body The anti-FOUC script goes in the head before any CSS loads. It checks localStorage for the theme preference and falls back to the system preference, then adds the dark class to the documentElement. This site (mejba.me) has a great dark mode implementation. The toggle in the bottom-right corner is smooth and the color scheme is well thought out with that emerald brand color.

1 Reply

PP
Priya Patel 5 days ago
Great write-up Emily! One thing to add: CSS custom properties work very well with dark mode. Instead of writing dark: for every single element, define your colors as CSS variables in :root and override them in .dark. Then use the variables in Tailwind with arbitrary values. Way cleaner than adding dark variants to every single utility class.

Post a Reply