I am using Tailwind CSS v4 and want to define custom colors that automatically switch between light and dark modes. Instead of using the dark:
prefix for every class, I want to manage color changes through CSS variables in my React project.
Here’s what I’m trying to achieve:
primary
, baseColor
, textColor
).dark:
in every class for better maintainability.I’ve tried adding CSS variables via :root
and the dark
class but want to ensure I’m following best practices for Tailwind v4.
How can I configure tailwind.config.ts and global CSS to achieve this?
From TailwindCSS v4 onwards, you can customize color appearance for any dark:
variant using @variant dark
. See bg-pink
in my example.
@custom-variant
directive - TailwindCSS v4 Docs@variant
directive - TailwindCSS v4 Docs@theme
directive - TailwindCSS v4 Docs - CSS-first configurationdocument.querySelector('button').addEventListener('click', () => {
document.documentElement.classList.toggle('dark');
});
<script src="https://unpkg.com/@tailwindcss/browser"></script>
<style type="text/tailwindcss">
/* changed the behavior of dark: (default: based on prefers-color-scheme) to work based on the presence of the .dark parent class */
@custom-variant dark (&:where(.dark, .dark *));
@theme {
--color-pink: #eb6bd8;
}
@layer base {
@variant dark {
--color-pink: #8e0d7a;
}
}
</style>
<button class="size-20 bg-pink dark:text-white">Click Here</button>
<div class="w-50 h-12 bg-purple-200 dark:bg-purple-900 dark:text-white">
Lorem Ipsum
</div>
Before v4, in v3, this was only possible if you explicitly knew how to declare dark:
, which was typically done with .dark { ... }
. See bg-pink
in my example.
tailwind.config = {
darkMode: 'class', // from v3.4.1 can use 'selector' instead of this
theme: {
extend: {
colors: {
pink: 'var(--color-pink)',
},
},
},
};
document.querySelector('button').addEventListener('click', () => {
document.documentElement.classList.toggle('dark');
});
<script src="https://cdn.tailwindcss.com"></script>
<style type="text/tailwindcss">
:root {
--color-pink: #eb6bd8;
}
.dark:root {
--color-pink: #8e0d7a;
}
</style>
<button class="size-20 bg-pink dark:text-white">Click Here</button>
<div class="w-50 h-12 bg-purple-200 dark:bg-purple-900 dark:text-white">
Lorem Ipsum
</div>