Tailwind CSS Dark Mode
Tailwind CSS includes a dark: variant that makes it easy to style your site differently when dark mode is enabled.
By default, Tailwind uses the prefers-color-scheme CSS media feature to detect the user's system preference. However, you can also configure Tailwind to support toggling dark mode manually using a CSS class.
Using the Dark Variant
To apply a style only when dark mode is active, prefix any utility class with dark:. For example, to set a dark background and light text:
Example
In this example, we've configured Tailwind to use the class strategy (see below), allowing us to toggle dark mode by adding or removing the .dark class from the html element.
Toggling Manually
To support manual toggling instead of relying solely on system preferences (like we did in the example above), you need to set the darkMode option to class in your tailwind.config.js file:
Now, instead of dark: utilities being applied based on media queries, they will be applied whenever the dark class is present earlier in the HTML tree (usually on the html or body tag).
Coming up, we'll explore strategies for managing duplication and reusing styles in a utility-first workflow.