Wouter Dijkstra

I make things like VoiPPush, FileFish & configbuddy.app.

Tailwind's @apply functionalities

Tailwind's @apply functionalities

Written by Wouter in Tailwind CSS on

Tailwind CSS is getting quite popular, and -in my opinion- rightfully so.

Just now I was reading an article by Johan Ronsse about why you should not use tailwind. Obviously, he does have some points. However, I would like to let you in on a little trick. A trick, in fact, I used to get this website up and running.

In his article he makes a point about overloading your project's HTML with 'a boatload of classes', and he's right. You'll end up using way more classes than you might ever need. For me, this is worth the hassle of not knowing what you're changing when making changes to your traditional style.css (or .sass - whatever).

Johan mentions having a lot of different versions of the same components in your code. Especially when you copy-paste your button component from one template to another, which you will eventually end up tweaking a little bit.

This is where this little (known?) Tailwind trick comes into play: The @apply directive.

Use @apply to inline any existing utility classes into your own custom CSS.

This is useful when you find a common utility pattern in your HTML that you'd like to extract to a new component.

Let me give you an example. This is a button's HTML from Covisitor's dashboard:

Tailwind Button Styling

I know, this is not the most beautiful button out there..

The @apply-trick

Tailwind offers the @apply directive out of the box.

Using this directive, we can create a button class and add all of our button styling, to get the same result. Like so:

Tailwind Button Styling

Instead of copy-pasting our button's classes, we can just add the button class to our <button> elements... And they will automatically all look exactly the same.

This might slow down development a bit, however, in the long run it saves a lot of time and trouble. Updating a style site-wide is way easier from now on.

The catch?

You might say: What about seperating your styles?

Right. That's what we liked about Tailwind. However, personally, I am okay with bundling styles for repetitive components. Using the apply directive for repeating elements should be what we're aiming for.

If you take some time to think about which elements you want to generate new custom classes for, you will enjoy maintaining and updating your codebase like never before.

In my opinion, this hybrid between regular, old-school CSS and Tailwind CSS is the way to go. Just use the @apply directive to create new, custom classes for common utility patterns (and don't worry about overwhelming your codebase with a boatload of classes).

For further reading, you can visit the official Tailwind docs.

Liked what your read? Spread the word: through Twitter of copy the link to other media.