Adding Dark Mode with Tailwind
How I setup dark mode on this website using Tailwind CSS
Using the Tailwind dark: property
Setting up dark mode for your website with Tailwind CSS is straightforward. As stated in Tailwind's documentation, adding the dark:
variant updates the specified style when the page is in dark mode. For example, to change the font color to white add `dark:text-white`
to the class of the element.
Should I use class or media?
In the tailwind config file, there's a darkMode property that can be to media or class. The former will use the client's preferences to choose between dark and light modes. The latter gives control to the developer and dark mode is used when dark shows up in the class tree. By setting class in the config, you can toggle between light mode and dark mode with the following line of code:
document.documentElement.classList.add('dark');
This adds the class dark to the root element and all styles using the dark property will be applied to your website. You should use this field when you want to control if a user sees light or dark mode. When using the media attribute tailwind will automatically configure the website to use the user's preferred style, based on their OS settings.
The best of both worlds!
On my website, I wanted to use the user's preferences to show them light or dark mode when they first come to my website but I also wanted to give them the option to change the style. To achieve this, I set the darkMode property to class, and on page load, I used the following code to get a user's preference:
window.matchMedia('(prefers-color-scheme: dark)').matches
Then I added a toggle button on the top right of my website. When you click the toggle it switches from light to dark mode and saves your current preference in local storage. When returning to the website I'm checking local storage and use the user's last selected mode instead of
Final thoughts
You can read more about setting up dark mode with Tailwind in the documentation, this is by far the simplest way I've found to add dark mode to your website. My main concern with using TailwindCSS is how verbose the classes can be making it difficult to understand the code. With dark mode, the number of classes added to your markup will increase. I've started using @apply, global styles, and the tailwind config to lower the amount of duplication and increase the readability of my code. Ultimately, it's easy to set up and more users are expecting a dark mode variant for your website!