next.jsfrontendtailwind-cssdarkmode

How customize theme selector in tailwind-css


I want to start with the dark theme and later add the light colors by adding the light: selector. Is it possible to do something like this?

<div class="bg-black light:bg-red-300 py-6">

...

</div>

i read about this plugin but its not what i want exactly


Solution

  • You could consider using a Tailwind Plugin to register custom static variants. For example, if light is to be identified by some parent light class, you could do:

    const plugin = require('tailwindcss/plugin')
    
    module.exports = {
      // …
      plugins: [
        plugin(function({ addVariant }) {
          addVariant('light', '.light &');
        }),
      ],
    };
    

    This would then allow you to use class names like light:bg-red-300 which would generate CSS like:

    .light .light\:bg-red-300 {
      …
    }
    

    Or if you wanted the opposite of dark: with its media query version, you could do:

    const plugin = require('tailwindcss/plugin')
    
    module.exports = {
      // …
      plugins: [
        plugin(function({ addVariant }) {
          addVariant('light', '@media (prefers-color-scheme: light)');
        }),
      ],
    };
    

    Which would generate:

    @media (prefers-color-scheme: light) {
      .light\:bg-red-300 {
        …
      }
    }
    

    Though really, if you only want a variant that applies when "not dark", you could consider reworking the logic of your classes a little:

    <div class="dark:bg-black bg-red-300 py-6">