String together responsive classes in TailwindCSS

Viewed 1586

I've been trying to Google this, but I'm either not using the right terms or nobody has asked my question yet.

Question: Is there a way to stack responsive classes in TailwindCSS? What I'd like to do is change something like:

class="grid gap-12 md:grid-cols-2 md:col-gap-12 md:py-16 lg:grid-cols-3 lg:py-12"

Into something more like:

class="grid gap-12 md:grid-cols-2:col-gap-12:py-16 lg:grid-cols-3:py-12"

I realize that it does not cut down that much in line length, but to me it just seems a little more sane grouping the responsive classes together. I'm new to TailwindCSS and just wanted to ask if this was possible.

4 Answers

For this to work, the tailwind CSS file would have to define a md:grid-cols-2:col-gap-12:py-1 class. It would also have to generate classes all other possible permutations for each breakpoint (up to some arbitrary maximum number of combined utilities). There are already 2877 classes for md, so once you start combining them this will get large very quickly. Just considering up to 3 utilities as you have here would result in about 24 million permutations for md and the same for each other breakpoint, so I don't think this would be practical.

This is actually something that is addressed in Windi.css, you can use group variants like this:

text-blue md:text-green lg:(p-2 m-2 text-red-400)

At the moment, it doesn't look as though tailwind has added this in, but I would be very surprised if they don't get round to doing so soon. Being able to ground breakpoints really helps keeping you class lists tidy... especially when tailwind can lead to some long, long lists.

Check out Windi if you have the chance, it's a good project, but I do think Tailwind will be introducing most of their (good) features before long.

One other thing helped me to achieve this is to use the screen directive.

https://tailwindcss.com/docs/functions-and-directives#screen

@media screen(md) {
    /* css to be overriden for >md screens */ 
}

or alternatively,

@screen md {
    /* css to be overriden for >md screens */
}

This way the responsive design doesn't clutter the standalone css. Can't find a way with inlined styles though.

Related