DEV Community

Cover image for Tailwind CSS - tips & tricks: ordering classes
Gianluca La Manna for This is Learning

Posted on

Tailwind CSS - tips & tricks: ordering classes

These days, I'm using this CSS framework almost every day. One of the things that was difficult for me was the order of the classes when we write something like this:

<div class="sm:grid-cols-1 gap-3 col-start-6 grid md:grid-cols-1 lg:grid-cols-3 col-span-6">
Enter fullscreen mode Exit fullscreen mode

In my mind, I have to find a rule for these orders. 🤯

Hank Schrader reading

The result is the same on the browser, but if we have clean and linear code, we can improve the comprehensibility, and we will be faster to understand it.

After some research, I found that there exists an official rule from tailwindcss

Rules

Any classes in the base layer must be sorted first, followed by classes in the components layer, and then finally classes in the utilities layer.

<!-- `container` is a component so it comes first -->
<div class="container mx-auto px-6">
  <!-- ... -->
</div>
Enter fullscreen mode Exit fullscreen mode

any classes that override other classes always appear later in the class list:

- <div class="pt-2 p-4"> <!-- before -->
+ <div class="p-4 pt-2"> <!-- after -->
    <!-- ... -->
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

Modifiers like hover: and focus: are grouped together and sorted after any plain utilities:

- <div class="hover:opacity-75 opacity-50 hover:scale-150 scale-125"> <!-- before -->
+ <div class="scale-125 opacity-50 hover:scale-150 hover:opacity-75"> <!-- after -->
    <!-- ... -->
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

Responsive modifiers like md: and lg: are grouped together at the end in the same order they're configured in your theme — which is smallest to largest by default:

- <div class="lg:grid-cols-4 grid sm:grid-cols-3 grid-cols-2">  <!-- before -->
+ <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4">  <!-- after -->
    <!-- ... -->
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

Any custom classes that don't come from Tailwind plugins (like classes for targeting a third-party library) must always be sorted to the front, so it's easy to see when an element is using them:

- <div class="p-3 shadow-xl select2-dropdown"> <!-- before -->
+ <div class="select2-dropdown p-3 shadow-xl"> <!-- after -->
    <!-- ... -->
  </div>
</div>

Enter fullscreen mode Exit fullscreen mode

That's a lot of rules! 🤯

Meme Hank Schrader


We have the solution

Yes, in fact I found an official plugins: Prettier Plugins for Tailwind

This will do it for us.

We can use this command:

npm install -D prettier prettier-plugin-tailwindcss
Enter fullscreen mode Exit fullscreen mode

And then add the plugin to your Prettier configuration file:

{
  "plugins": ["prettier-plugin-tailwindcss"]
}
Enter fullscreen mode Exit fullscreen mode

That's all, guys. See you next time 👋🏻

Top comments (0)