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">
In my mind, I have to find a rule for these orders. 🤯
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>
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>
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>
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>
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>
That's a lot of rules! 🤯
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
And then add the plugin to your Prettier configuration file:
{
"plugins": ["prettier-plugin-tailwindcss"]
}
That's all, guys. See you next time 👋🏻
Top comments (0)