Utility-first frameworks like Tailwind CSS are incredibly powerful, but they often result in long class lists that can become difficult to read and maintain. Today, you can automate sorting and stop worrying about formatting disputes with the release of the official Prettier plugin for Tailwind CSS.
This plugin automatically scans your templates for class attributes and sorts them according to Tailwind's recommended class order.
1. Quick Start Installation
To get started, install prettier-plugin-tailwindcss as a dev-dependency:
npm install -D prettier prettier-plugin-tailwindcssThen, add the plugin to your Prettier configuration file:
{
"plugins": ["prettier-plugin-tailwindcss"]
}If you are using the Prettier CLI, you can also load the plugin using the --plugin flag:
prettier --write --plugin=prettier-plugin-tailwindcss .2. How the Sorting Works
The plugin automatically organizes classes in the same order they are loaded in the final CSS bundle:
- Base Styles: Classes in the base layer come first.
- Components: Classes in the components layer (like custom custom button components) follow.
- Utilities: Utilities are sorted based on box-model specifications, placing layout and positioning utility classes first (e.g.,
flex,grid,margin,padding), followed by decorative classes (e.g.,bg-color,border-radius,shadow-md).
Before vs. After Example
<!-- Before -->
<button class="text-white px-4 sm:px-8 py-2 sm:py-3 bg-sky-700 hover:bg-sky-800">
Submit
</button>
<!-- After -->
<button class="bg-sky-700 px-4 py-2 text-white hover:bg-sky-800 sm:px-8 sm:py-3">
Submit
</button>3. Order Hierarchy Details
Here is the exact precedence used by the plugin:
Layout vs. Styling
Layout attributes (like display, positioning, box size) are pushed to the front to establish high-impact characteristics, while colors and borders are placed towards the end:
<!-- Component classes first -->
<div class="container mx-auto px-6">
<!-- ... -->
</div>Modifiers & Pseudo-classes
Modifiers (like hover:, focus:, active:) are grouped together and sorted after their base utility:
<div class="scale-125 opacity-50 hover:scale-150 hover:opacity-75">
<!-- ... -->
</div>Responsive Design
Responsive variants (like sm:, md:, lg:) are grouped at the very end in ascending size order (smallest to largest viewport):
<div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4">
<!-- ... -->
</div>Custom Classes
Any custom class names that are not part of your Tailwind configuration or plugins are moved to the front:
<div class="custom-dropdown p-3 shadow-xl">
<!-- ... -->
</div>Conclusion
By enforcing an opinionated formatting style, you save time, reduce merge conflicts, and keep your codebase consistent across team members.
Give it a try and never manually arrange another Tailwind utility class list again!
