Huy's Notes
Dark Mode for Tailwind

Dark Mode for Tailwind


There's already an article showing how to apply dark mode in Tailwind CSS based on OS's setting. But in a real application, you might want to have fully control over it, since user might want to use dark mode in your application only, not enable it system wide.

The solution would be, put a dark-mode class to some top level container such as <body> tag, and add a variant in Tailwind CSS, so it could be used like this:

<div class="bg-gray-100 dark-mode:bg-gray-800"></div>

To do so, create a new plugin in your tailwind.config.js like this:

plugins: [
    plugin(function({ addVariant, e }) {
        addVariant('dark-mode', function({ modifySelectors, separator }) {
            modifySelectors(function({ className }) {
                return `.dark-mode .${e(`dark-mode${separator}${className}`)}`;

You might want to apply this variant for whatever attribute you want to use, for example:

variants: {
    backgroundColor: [ 'hover', 'focus', 'dark-mode' ],
    textColor: [ 'hover', 'focus', 'dark-mode' ],
    borderColor: [ 'hover', 'focus', 'dark-mode' ],

Referred in

If you think this note resonated, be it positive or negative, please feel free to send me an email and we can talk.