Tailwind v4 Dark Mode Not Working? The @custom-variant Fix Checklist
October 3, 2026 | 9 min read | Tailwind CSS
By Syed · Frontend Engineer & Creator of UITweak
You upgraded to Tailwind v4. Your dark: classes do nothing. The darkMode: 'class' setting from your old config is silently ignored. Your theme toggle button is dead, but here is the strange part: dark mode still follows the operating system. This is the most reported Tailwind v4 dark mode problem, and it is not a mystery. It is a short checklist. Work through the six fixes below in order and one of them will be yours.
30-second diagnosis first: open DevTools, click your toggle, and answer two questions. (1) Does the <html> element actually gain the dark class? (2) Does your compiled CSS contain selectors like .dark .dark\:bg-gray-900? If the class never appears, jump to Fix 4. If the selectors are missing from the CSS, your problem is Fix 1 or Fix 2. If both look right, keep reading from Fix 3.
What Changed in v4 (60 Seconds of Background)
In v3, class-based dark mode was a config option: darkMode: 'class' in tailwind.config.js. Tailwind v4 moved to CSS-first configuration, so there is no config file key anymore, and the old key is ignored without any warning. In v4, the dark: variant defaults to the prefers-color-scheme media query, which is why your site still follows the OS setting while your toggle does nothing. To get class-based dark mode back, you define the variant yourself with one line of CSS. That single line is Fix 1.
Fix 1: Add the Missing @custom-variant Line
This is the cause in most cases. Add this to your main CSS file:
@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *));This tells Tailwind that dark: means "when an ancestor has the dark class" instead of "when the OS prefers dark". The &:where(...) wrapper is deliberate: :where() keeps the selector at zero specificity so your dark styles do not accidentally outrank (or get outranked by) other rules. Do not "simplify" it to .dark &; you will inherit a specificity problem that shows up later as Fix 6.
Confirm it worked: rebuild and search your compiled CSS for .dark. If the selectors are there now, you are done. A fast way to check without digging through build output: paste your stylesheet into our free Tailwind Config Visualizer and look at the generated CSS. If no .dark selectors appear in the output, the variant never registered and the problem is here or in Fix 2.
Fix 2: The Directive Must Come After @import
Order matters. @custom-variant has to appear after @import "tailwindcss" in your CSS file. Placed before the import, it may not register, and Tailwind will not warn you. This bites people who keep a "custom stuff at the top" section in their stylesheet:
/* WRONG: variant defined before Tailwind loads */
@custom-variant dark (&:where(.dark, .dark *));
@import "tailwindcss";
/* RIGHT */
@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *));Fix 3: Match the Selector to Your Toggle
The snippet in Fix 1 listens for a dark class. But many apps toggle a data-theme="dark" attribute instead (DaisyUI-style setups and several component libraries do this). If your JavaScript sets an attribute while your CSS listens for a class, DevTools will show the attribute changing and absolutely nothing happening. They must agree. For attribute-based toggling, define the variant like this:
@import "tailwindcss";
@custom-variant dark (&:where([data-theme="dark"], [data-theme="dark"] *));Pick one strategy per project. Mixing a class toggle in one place and an attribute toggle in another is a reliable way to get a bug report at midnight.
Fix 4: Toggle the Class on <html>
The selector &:where(.dark, .dark *) means the dark class must sit on an ancestor of every element you style. The safe target is document.documentElement (the <html> element). The classic mistake is toggling the class on a wrapper <div> that does not actually wrap everything: headers, modals, and portals rendered outside that div stay light. In vanilla JS:
// right: <html> wraps everything
document.documentElement.classList.toggle("dark");In React/Next.js, do the same via document.documentElement in an effect or event handler. If your 30-second diagnosis showed the class landing on some inner div instead of <html>, this is your fix.
Fix 5: Clear the Stale Build
Symptom pattern for this one: dark mode works perfectly on localhost and is broken in production. Your deploy is serving cached CSS from before the fix. Clear the build cache on your host (Vercel, Netlify, and Cloudflare all have a "clear build cache and redeploy" option) and redeploy. Also rule out an aggressive service worker serving an old stylesheet. If a fresh incognito window shows the fix working, it was cache all along.
Fix 6: Something Is Overriding Your Dark Styles
If .dark selectors exist in the CSS and the class toggles correctly, but elements still do not change, something with higher specificity is winning. Inspect the element in DevTools: if you see the .dark .dark\:bg-gray-900 rule present but struck through, you have a cascade problem, not a dark mode problem. Usual suspects: inline styles, a later non-dark utility fighting the dark one, or a custom component class defined without @layer (unlayered styles beat layered ones). This is also why Fix 1 uses :where(): it keeps the dark selector's specificity at zero so the normal utility ordering decides, which is what you want.
Bonus: Kill the White Flash on Load
Once the toggle works, you will notice a new annoyance: the page flashes light mode for a split second before your JavaScript adds the dark class. Fix it with a tiny inline script in <head> that runs before first paint:
<head>
<script>
try {
if (
localStorage.theme === "dark" ||
(!("theme" in localStorage) &&
matchMedia("(prefers-color-scheme: dark)").matches)
) {
document.documentElement.classList.add("dark");
}
} catch (e) {}
</script>
</head>Because it runs synchronously in the head, the class is in place before the browser paints anything. No flash, no layout shift.
Quick Recap
- Add
@custom-variant dark (&:where(.dark, .dark *));to your CSS. - Place it after
@import "tailwindcss". - Make the selector match your toggle: class vs
data-theme. - Toggle the class on
<html>, not an inner div. - Clear build cache and redeploy if production disagrees with local.
- If rules exist but lose, check DevTools for specificity overrides.
For the other v4 migration gotchas (renamed gradient utilities, @apply failures, @theme tokens being ignored), see our Tailwind v4 common errors and fixes guide, and for the theming system itself, the Tailwind v4 @theme guide.
# Expansion draft: tailwind-v4-dark-mode-fix-guide
Debugging Walkthrough: Tracing a Dead Toggle End to End
The six fixes in the main guide cover the causes. This is the order I actually check them in when someone hands me a broken dark mode, because the order matters: each step rules out a whole category before I touch code.
**Step 1: watch the toggle.** Open DevTools, click the toggle, and look at the <html> element. If the dark class appears and disappears, the JavaScript is fine and the problem is in CSS generation. If nothing happens, stop debugging CSS entirely: the bug is in the toggle handler, the state management, or a hydration mismatch that wipes the class after the client takes over. In Next.js apps, that last one is common: a server component renders without the class, the client hydrates, and React removes the class your inline head script added because the server HTML did not have it. The fix there is suppressHydrationWarning on the <html> element, which is the standard approach for theme toggles in the App Router.
**Step 2: check the compiled CSS.** Search the built stylesheet for .dark. If the selectors exist, generation works and the problem is specificity or targeting: the class lands on the wrong element, or a later rule wins. If they are missing, the @custom-variant line never registered, which points at Fix 1 or Fix 2 of the main guide.
**Step 3: inspect one element.** Pick a single element with a dark: class, find its rule in DevTools, and read the strike-through state. Rule present but struck through means something with higher priority wins, and DevTools shows you exactly which rule. Rule absent from the element's matched rules while present in the stylesheet means the selector does not match: the dark class is on the wrong ancestor, or you are mixing class and attribute strategies.
I do these three steps before reading a single line of CSS source. They take about two minutes and they convert "dark mode is broken" into one of three precise statements: the toggle does not fire, the CSS was never generated, or the CSS loses. Each statement has exactly one fix.
Dark Palettes the Clean Way: Redefine Tokens, Don't Duplicate Classes
Once the toggle works, the next question is how to write the dark styles themselves. The beginner pattern is duplicating every color class: bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100 on every element. It works, and on a small site it is fine. On a large one it doubles the color decisions scattered across your markup, and when the palette changes you hunt through hundreds of files.
The cleaner pattern uses semantic tokens. Define what a surface color means, then redefine the token under .dark:
@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *));
@theme {
--color-surface: oklch(1 0 0);
--color-ink: oklch(0.21 0.02 260);
}
.dark {
--color-surface: oklch(0.21 0.02 260);
--color-ink: oklch(0.98 0.01 260);
}Now markup uses bg-surface text-ink with no dark: variants at all, and the theme flips by redefining variables. This works because @theme tokens are real CSS custom properties on :root, so the cascade re-resolves them under .dark. I prefer this for any project with more than a handful of pages. The tradeoff is indirection: a new developer reading bg-surface has to look up what surface means in each theme. For a design system with documented tokens that is a feature, not a bug. For a weekend project it is overkill, and the dark: prefixes are more readable.
One caution: do not mix the two patterns for the same property. A dark:bg-gray-900 on an element that also uses bg-surface creates two competing definitions, and whichever the next developer touches first will confuse them. Pick per project, document it once, and move on.
The Hybrid Setup: Respect the OS Until the User Chooses
The main guide covers class-based toggling, but the best user experience is a hybrid: follow the operating system by default, and let an explicit user choice override it. The inline head script in the Bonus section already does half of this: it checks localStorage first, then falls back to prefers-color-scheme.
The half people miss is listening for OS changes while the page is open. If the user has never chosen explicitly, a system theme change at sunset should flip the site too:
useEffect(() => {
if (localStorage.theme) return; // explicit choice wins, do nothing
const mq = matchMedia("(prefers-color-scheme: dark)");
const apply = () => document.documentElement.classList.toggle("dark", mq.matches);
apply();
mq.addEventListener("change", apply);
return () => mq.removeEventListener("change", apply);
}, []);The key detail is the early return. Once the user picks a theme, their choice is stored and the OS listener stands down. Without that guard, the site fights the user's explicit toggle every time the OS changes, which is the kind of bug that generates exactly one confused support ticket and a hundred silent eye-rolls. Also note the older addListener API is deprecated in favor of addEventListener("change", ...); use the latter.
Dark Mode and Media: Images, Video, and Iframes
Utilities handle your UI. They do nothing for your content. Photographs, illustrations, embedded videos, and third-party iframes do not respond to a dark class, and a bright white product photo on a dark page is the most common "dark mode looks unfinished" complaint I hear.
For images you control, the practical options are: ship two variants and swap with a dark:-toggled pair (one hidden dark:block, one dark:hidden), or design images that work on both, like illustrations with transparent backgrounds instead of white ones. The swap doubles image weight, so I reserve it for logos and key illustrations, not every photo.
For video and iframes, CSS filters are the blunt instrument: dark:invert or a brightness reduction can rescue an embedded widget that has no dark theme of its own. It is a hack and it looks like one on colorful content, so use it sparingly and never on your own media. The honest fix for embeds is checking whether the provider offers a dark theme parameter. Most major embed providers do, and a theme-aware embed URL beats a filter every time.
Prevention Checklist for New Projects
If you are starting fresh rather than fixing a migration, five decisions made on day one prevent the entire guide:
1. **Choose class or attribute strategy before writing any component.** One line in the README. Every toggle, every variant definition, every test follows it.
2. **Add the @custom-variant line in the same commit as the Tailwind v4 setup.** The bug in the main guide exists because the line was forgotten during migration. It cannot be forgotten if it ships with the initial config.
3. **Put the dark class toggle behind a single function.** One setTheme() helper used by every toggle button, the head script, and the OS listener. Three places setting the class independently is how the class-vs-attribute mismatch starts.
4. **Decide tokens versus dark: prefixes for colors on day one.** See the token section above. Either is defensible; mixing them is not.
5. **Test the toggle in a private window after every deploy.** The stale-build failure from Fix 5 is a deploy problem, not a code problem, and a thirty-second private-window check catches it before users do.
Frequently Asked Questions
Why did v4 remove darkMode: 'class'?
It did not remove the capability, it moved it. v4 uses CSS-first configuration, so JavaScript config keys were replaced by CSS directives. One @custom-variant line replaces the old config option and gives you more control (any selector, not just a class).
Can I use data-theme="dark" instead of a class?
Yes. Define the variant with the attribute selector as shown in Fix 3, and make sure your toggle sets the attribute on <html>. Just do not mix class toggling and attribute toggling in the same project.
Do stacked variants like dark:hover: still work?
Yes, once the custom variant is registered. dark:hover:bg-gray-800 compiles to the hover state nested inside the dark selector. Keep a consistent variant order across your codebase so the generated selectors stay predictable.
Dark mode works, but the page flashes white first. Why?
Your JavaScript adds the dark class after the first paint. The inline head script in the bonus section sets the class before anything renders, which removes the flash entirely.
My dark: styles work in dev but not in production.
That is almost always a stale build cache serving pre-fix CSS (Fix 5). If a clean rebuild does not help, check that your production build actually includes the stylesheet with the @custom-variant line: some setups have separate CSS entry points for dev and prod.
Verify the fix: paste your updated stylesheet into the free Tailwind Config Visualizer and confirm .dark selectors appear in the generated CSS. If they do and your toggle targets <html>, dark mode will work.