Dark Mode
Using Tailwind CSS to style your site in dark mode.
Now that dark mode is a first-class feature of many operating systems, it’s becoming more and more common to design a dark version of your website to go along with the default design.
To make this as easy as possible, Tailwind includes a variant that lets you style your site differently when dark mode is enabled:
By default this uses the prefers-color-scheme
CSS media feature, but you can also build sites that support toggling dark mode manually using the .
Toggling dark mode manually
tailwind.config.js
Now instead of dark:{class}
classes being applied based on , they will be applied whenever dark
class is present earlier in the HTML tree.
If you’ve set in your Tailwind config, be sure to add that to the dark
class. For example, if you have a prefix of tw-
, you’ll need to use the tw-dark
class to enable dark mode.
How you add the class to the html
element is up to you, but a common approach is to use a bit of JS that reads a preference from somewhere (like localStorage
) and updates the DOM accordingly.
The class
strategy can be used to support both the user’s system preference or a manually selected mode by using the .
spaghetti.js
Again you can manage this however you like, even storing the preference server-side in a database and rendering the class on the server — it’s totally up to you.
Customizing the class name
Some frameworks (like NativeScript) have their own approach to enabling dark mode and add a different class name when dark mode is active.
You can customize the dark mode selector name by setting darkMode
to an array with your custom selector as the second item:
tailwind.config.js