Search code examples
cssreactjstailwind-csstailwind-in-jstailwind-variants

How to define custom utility with media queries in Tailwind?


So, I have been trying to find a way to make my custom utilities, e.g., padding-root-inline responsive to screens sizes. So far, I know that I can do something like this-

@layer utilities {
    .padding-root-inline { ... }
    .padding-root-inline-sm { ... }
}

and then use screen modifiers like this-

<section class="padding-root-inline max-sm:padding-root-inline-sm"></section>

But this still doesn't seem convenient as I have to write the varient class along with the base class in each of the components I use it in. What I want is something like this-

@layer utilities {
    @media all and (max-width: theme('screens.xs')) {
        .padding-root-inline {
            padding-inline: calc(theme('padding.root-inline') - 2rem);
        }
    }
}

so that I could just say padding-root-inline and it would be responsive on its own, without the need to say sm:padding-root-inline-sm.


Solution

  • You can directly define the media queries within your custom utility:

    @layer utilities {
        .padding-root-inline {
            padding-inline: calc(theme('padding.root-inline') - 2rem);
    
            @media (min-width: theme('screens.sm')) {
                padding-inline: ...
            }
    
            @media (min-width: theme('screens.md')) {
                padding-inline: ...
            }
    
            //...and so on
        }
    }