Fixing Tailwind Dark Mode with Custom Variants
When rewriting this blog, I migrated to Tailwind v4. After the migration, I realized that light mode colors were not applied when I switched to light mode. This seemed like something a coding agent would easily fix so I asked Cursor & Claude to fix it. The fixes were dirty as both ended up using !important or inline styles to ensure that light mode colors were applied correctly.
If you have worked with css, you'd know that these are things you only reach for when there is no other solution. When I read the Tailwind docs I found out that Tailwind v4 applies utilities based on the OS preferred color scheme by default. Since my OS preferred color scheme is dark, dark mode styles were applied even in light mode. The correct solution was to override this behavior.
Since I was using the .dark class to implement theme toggling, I had to override the default behavior by adding the highlighted line of code to my global css file.
/* in the global.css file */
@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *));This single line tells Tailwind:
- Only apply
dark:*utilities when the.darkclass is present - Ignore the system's
prefers-color-schemesetting - Give you full control over theme switching via JavaScript
References
Key Takeaways
- Both coding agents were fixing a symptom and not a root cause. Spotting something like this requires some background knowledge.
- Your agent might be trained on data that isn't up to date, providing a link to the latest docs when working with recently updated frameworks improves the results.
- Tailwind v4 defaults to the preferred OS color scheme when switching themes.
Related Posts (3)
How to use Next.js's connection() API to opt specific components into dynamic rendering while keeping the rest of your page statically generated.
Git Rebase --onto
1 min readLearned about git rebase --onto for moving branches to a different base.