Repeating Tailwind CSS Styles

Kevin

So far I am loving the easy flow that Tailwind enables. The current project I am applying it to has some of the original styles around in CSS Modules and some global.css, so it's a little bit slower going to both rig the Tailwind and remove the old styles, and even still things seem to be flowing nicely.

But after reading the documentation and settling in to use TW, I was concerned about the huge amount of utility classes that fill the markup, and what to do with oft-repeated styles.

The Problem

The documentation on this subject isn't exactly the most helpful, and proposes just a couple solutions:

  • Bust elements with repetitious styles into components
  • Use your IDE to do multi-cursor editing 🤡

I mean, that'll work and all, but I feel like it leads the developer towards too much abstraction or just really head-achey acreen squinting while not solving the maintainability problem much at all.

Take for example am <h3> style that is all over an app. I could fall back on my global CSS for a style to rule them all, and that's not too bad. But since I'm trying to go at this with a completely Tailwind approach, I want to avoid that.

Should I make a `<Header3 />` component to use all over the project? That's ludicrous.

Solution

Since a well-defined and great working TW style pretty much boils down to a string of all the classes needed, I can break out my h3 looks and refer wherever I need it with the variable name:

Blog Image

Then it can be defined elsewhere. How about in a `tailwindStyles.ts` file in the `styles/` directory with other handy, repeating styles?

Blog Image

With this setup, my components and mark up stay so much cleaner throughout the project and fix that feeling of utility classes swarming everywhere. Then I know when I see those TW classes pop up that they are likely addressing specific issues within that bit of UI.

Caution:

I have only started trying this out, so I don't yet know if it creates any fatal flaws. I did run into a misstep where it appeared as through my project could not compile the tailwind CSS that I had just added this way (confusion contributed to by NextJS's sluggish cache not breaking things as immediately as you'd assume).

Just be sure if you add a styles reference file with stock TW class strings that they are also added to the `tailwind.config.js` file. This is how mine came out:

Blog Image