When using Tailwind CSS in a React or Next.js app, the order of classes in the className
property doesn’t seem to matter for functionality.
However, I noticed it can get messy and inconsistent, especially for readability and maintaining a clean codebase. For instance:
<article className="gap-3 rounded-lg border p-5 hover:bg-muted/60 flex">
{title}
</article>
Even though this works fine, the classes are out of order and less readable.
To fix this issue, I used Prettier with a Tailwind CSS plugin to automatically sort my classes in a consistent order:
Install Dependencies:
I installed Prettier and the Tailwind CSS plugin as devDependencies:
pnpm install -D prettier prettier-plugin-tailwindcss
(You can also use
npm install -D prettier prettier-plugin-tailwindcss
if you’re using npm. I prefer pnpm because it’s faster and more storage-efficient.)
Configure Prettier:
I created a .prettierrc
file in the root directory and added the following configuration:
{
"plugins": ["prettier-plugin-tailwindcss"]
}
Class Sorting in Action:
When I saved a file, Prettier automatically reordered the classes for better readability. For example:
<article className="gap-3 rounded-lg border p-5 hover:bg-muted/60 flex">
{title}
</article>
<article className="flex gap-3 rounded-lg border p-5 hover:bg-muted/60">
{title}
</article>
Another example:
<div className="lg:grid-cols-4 grid sm:grid-cols-3 grid-cols-2">
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4">
Now, all my Tailwind CSS classes are consistently ordered with minimal effort—Prettier and the plugin take care of it when I save my files!
Here’s a link to TailwindCSS page to read more.