Tailwind v4 has changed significantly the light/dark theme design due to the removal of tailwind.config.js
file.
In Tailwind v3 this is how I changed the custom CSS properties depending on the theme:
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--background: 0 0% 4%;
--foreground: 0 0% 98%;
}
.dark {
--background: 0 0% 98%;
--foreground: 0 0% 4%;
}
}
However, in Tailwind v4, the @theme
, @variant
and @custom-variant
keywords have been introduced.
I have read the docs and tried to use them for getting the same result, for example: (This does NOT work)
@import "tailwindcss";
@import "@fontsource-variable/montserrat";
@theme {
--color-foreground: 0 0% 8%;
--color-background: 0 0% 98%;
}
@custom-variant dark (&:where(.dark, .dark *));
@variant dark {
@theme {
--color-foreground: 0 0% 98%;
--color-background: 0 0% 3.9%;
}
}
Which is the correct way of doing this in Tailwind v4?
I found an article which shows a way of doing what I need, albeit the code is a bit verbose and uses the data-theme
attribute instead of a CSS class, but it works as a charm:
@import "tailwindcss";
@theme {
--color-foreground: var(--theme-color-foreground);
--color-background: var(--theme-color-background);
}
@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *));
@layer base {
[data-theme="light"] {
--theme-color-foreground: hsl(0 0% 8%);
--theme-color-background: hsl(0 0% 98%);
}
[data-theme="dark"] {
--theme-color-foreground: hsl(0 0% 98%);
--theme-color-background: hsl(0 0% 3.9%);
}
}
I am open for better solutions!