Intro
To support dark mode with Tailwind, you would usually write something like this according to the docs.
<div className="bg-black dark:bg-white">
<p className="text-white dark:text-black">text</p>
</div>
This makes your already-long tailwind classes become even longer.
To fix this, we can use semantic colors and change colors dynamically based on the current theme. (semantic colors mean colors that are named based on their purposes, like success
, warning
, background
, and primary
)
Steps
In index.html, make sure you can toggle the class dark.
When dark mode is on.
<html class="dark" />
When dark mode is off.
<html />
Note: In a real project, you might want to detect the user preference using window.matchMedia("(prefers-color-schema: dark));
In your globals.css
or any css files
:root {
--color-foreground-primary: black;
--color-background-primary: white;
}
.dark {
--color-foreground-primary: white;
--color-background-primary: black;
}
By adding this, the variables will dynamically change when the website is in dark mode.
And in tailwind.config.js
.
...
theme: {
extend: {
colors: {
foreground: {
primary: "var(--color-foreground-primary)",
},
background: {
primary: "var(--color-background-primary)",
},
},
},
},
...
Now, in your html, you can do the following.
<div className="bg-background-primary">
<p className="text-foreground-primary">text</p>
</div>
Hope this is useful to you.
Let me know how you support dark mode in your projects!
Top comments (0)