Tailwind supports dark mode out of the box, by simply prefixing a typical class with
dark:. In simple cases, you can easily create a website which toggles styles based on whether the user has dark mode enabled:
However as your application grows, with more and more markup, reproducing this code over and over becomes cumbersome and a pain to change down the line (e.g. if we wanted to swap out
Instead we can take advantage of CSS variables and the Tailwind configuration to make this process much more streamlined. Assuming we're using the "class" based approach to using dark mode, go ahead and create a few custom CSS variables within your entry
We've just created two variables called
--dark-background with their own hex values. We then create a new
--background variable and assign this the light or dark variant depending on whether our
html element has the
dark class name.
tailwind.config.js file, we can now create a custom color, which uses the
Tailwind will now produce a new set of CSS classes based on our own "custom" color set. Now instead of duplicating the class names within our elements we can simply write the following:
Whenever the page swaps between dark and light mode, our variable will be updated, having a knock on effect which updates our own class name, simple! We've also got the added benefit of having a single source of truth for our background color.
You could further extend this to support text colors, border colors and more following the same steps... simple!