tailwind-cssmodifierutilities

How can I group several Tailwind CSS utilities under one modifier?


I'm using Tailwind's default breakpoint values in a TypeScript + React project compiled with Vite. But I noticed that in my project and on a section of their documentation that both repeated instances of the same modifiers within one element. In the doc's case md::

<img class="h-48 w-full object-cover md:h-full md:w-48" src="/img/building.jpg" alt="Modern building architecture">

Is there a way to group h-full and w-48 under one md: modifier to make certain styles more readable and easier to locate?

My Attempted Solution

Using Tailwind's default color palette and default breakpoint values, I made "Hello World" take on an orange background and the heaviest available font weight when the screen size is equal to or greater than sm's default minimum width of 640px:

<h1 className="sm:bg-orange-500 sm:font-black">Hello World</h1>

To reproduce the same result using one instance of the sm modifier within the same <h1> element, I tried adding curly braces around utility classes grouped together with commas:

<h1 className="sm:{bg-orange-500, font-black}">Hello World</h1>

Solution

  • You can use tailwindcss/plugin to apply multiple rules if the breakpoint matches

    first you need to add the following code to your tailwind.config.js file

    /** @type {import('tailwindcss').Config} */
    
    export default {
      content: [
        "./index.html"
        "./src/**/*.{js,ts,jsx,tsx}"
      ],
      theme: {
        //...
      },
      plugins: [
        // add the following lines
        require('tailwindcss/plugin')(({ matchUtilities }) => {
          matchUtilities({
            'x': (value) => ({
              [`@apply ${value.replaceAll(',', ' ')}`]: {}
            })
          })
        })
      ]
    }
    

    and now you can apply multiple rules that matches with the breakpoint/state/etc e.g.:

    <!-- then -->
    <section className='text-[#f00] text-[25px] font-semibold md:text-[#0f0] md:text-[36px] md:font-bold'>
      {...}
    </section>
    
    <!-- now -->
    <section className='text-[#f00] text-[25px] font-semibold md:x-[text-[#0f0],text-[36px],font-bold]'>
      {...}
    </section>