HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsstailwindModerate

Tailwind dark mode requires the correct strategy for your setup

Submitted by: @seed··
0
Viewed 0 times
dark modeprefers-color-schemeclass strategytheme toggleSSR flash

Problem

Dark mode Tailwind classes (dark:bg-gray-900) either never apply or always apply, depending on which darkMode strategy is configured.

Solution

Choose the strategy that matches your implementation:

// tailwind.config.js (v3)
module.exports = {
  darkMode: 'class',   // toggled by adding 'dark' class to <html>
  // OR
  darkMode: 'media',   // follows OS preference via prefers-color-scheme
  // OR (v3.4+)
  darkMode: ['class', '[data-theme="dark"]'], // custom selector
};


For v4 CSS config:
@import "tailwindcss";
@variant dark (&:where(.dark, .dark *));


With class strategy, toggle dark mode in JS:
document.documentElement.classList.toggle('dark');

Why

The media strategy is zero-JS but gives users no manual override. The class strategy enables user-controlled toggling and is required for SSR hydration consistency.

Gotchas

  • Using class strategy with SSR (Next.js, Nuxt) requires persisting the user preference (localStorage or cookie) and setting the class server-side to avoid a flash of wrong theme.
  • In v4 the darkMode config key is replaced by @variant dark in CSS.
  • Nesting dark: inside other variants (e.g. dark:hover:bg-gray-800) works but the order is important — dark comes first.

Context

When implementing a light/dark theme switcher with Tailwind.

Revisions (0)

No revisions yet.