🚀 Promote your brand here — Reach our amazing audience!
Home / articles / fix tailwind dark light mode toggle

Fixing Dark/Light Mode in Tailwind V4 Without Prefers-Color-Scheme

By Hisham · Published on October 06, 2025

By default, Tailwind may generate CSS that follows the system preference using @media (prefers-color-scheme: dark). This can prevent your toggle button from working properly. Here is how to fix it.

1. Remove Prefers-Color-Scheme in Tailwind

Edit your app.css and add the following:

@tailwind utilities;

/* Custom variant for class-based dark mode */
@custom-variant dark (&:where(.dark,.dark *));

@theme {
--darkMode: class;
...
}

2. Create a Toggle Button

Add a button anywhere in your HTML:

<button onclick="toggleTheme()" id="theme-btn">Toggle Theme</button>

3. Add the Toggle JS

function toggleTheme() {
  document.documentElement.classList.toggle("dark");

  // Save preference
  if (document.documentElement.classList.contains("dark")) {
    localStorage.setItem("theme", "dark");
  } else {
    localStorage.setItem("theme", "light");
  }
}

// Apply saved preference on page load
const savedTheme = localStorage.getItem("theme");
if (savedTheme === "dark") {
  document.documentElement.classList.add("dark");
} else {
  document.documentElement.classList.remove("dark");
}

4. Build Tailwind Assets

Run:

npm run build

This will regenerate CSS with your class-based dark mode and remove any @media (prefers-color-scheme: dark) rules.

5. Additional Notes

  • Clear browser cache to make sure old media-based styles aren’t applied.

  • Ensure all your dark mode styles use dark: and that they now respond to the .dark class.

  • Toggle button works perfectly and ignores system settings.

Following this method, your Tailwind dark/light mode will now be fully controlled by the user, not the system, and your toggle button will work as expected.

🚀 Promote your brand here — Reach our amazing audience!