DEV Community

Discussion on: TailwindCSS @apply - the right approach?

pp profile image
Paweł Ludwiczak Author • Edited on

I'm not sure if I agree with this one. I have a codebase that doesn't use any dynamically generated components (like React - where one file can be responsible for one component). It's more static codebase - with files for entire views and/or parts of it. There's definitely not a react-like component for Buttons - you have to create them by hand.

So it makes perfect sense for me to use utility classes to set up layouts, grids, etc but I'd had to repaste 20 exactly the same utility classes for every of my button

<button class="bg-red text-white px-4 py-2 ...">...</button>
Enter fullscreen mode Exit fullscreen mode

Instead it makes sense to create old-school cool button.css file with something like

.btn {
  @apply bg-red text-white px-4 py-2 ...;
Enter fullscreen mode Exit fullscreen mode

And while using utility classes elsewhere in the views (for defining some generic layouts and grid), I still need to create more old-school CSS-only components. You can say that I could do something like this:

.btn {
  background: var(--red);
  color: var(--white);
  padding: var(--s2) var(--s4);
Enter fullscreen mode Exit fullscreen mode I don't have to use @apply but then the question is how to keep my CSS vars in sync with Tailwind (which I'm not sure supports vars that well - I could be wrong here though).

That being said, I think it makes perfect sense to use utility classes in HTML in some places with combination of @apply approach for creating pseudo-components.