Search code examples
pluginstailwind-cssthemesdarkmode

Tailwind custom theme prefix like dark:{class}


I am working on a site that has two types of customers "b2c" & "b2b". I want to style the pages differently depending on which type of customer accesses the page.

Is there a way to define a custom tailwind theme prefix like b2c:bg-blue-400 & b2b:bg-green-400

I have seen examples of this done fx. headlessui tabs

Futhermore is it possible to also allow dark mode options like b2c:text-black dark:b2c:text-white

I've tried to modify the default theme, but I cannot find a solution that lets me choose between two different class options depending on a given theme.


Solution

  • You could consider using a Tailwind Plugin to register custom static variants. For example, if b2c and b2b are to be identified by some parent class b2c and b2b respectively, you could do:

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

    These would then allow you to use class names like b2c:bg-blue-400 and b2b:bg-green-400, which would generate CSS like:

    .b2c .b2c\:bg-blue-400 {
      …
    }
    
    .b2b .b2b\:bg-green-400 {
      …
    }
    

    Additionally, these new variants will automatically work with other variants, like dark:b2c:text-white, which would geneate something like:

    @media (prefers-color-scheme: dark){
      .b2c .dark\:b2c\:text-white {
        …
      }
    }