Sort Tailwind classes automatically with Prettier

prettier-tailwindcss

Without class sorting, Tailwind class lists end up in random order. Layout, spacing, color, and typography classes mix together. The component works, but you have to read the whole list every time to see what it does.

The problem with unsorted classes

Look at this component:

<div className="bg-white px-6 pt-4 text-sm shadow-sm mt-2 mb-4 rounded-lg border">

It works, but the order is random. Spacing sits between colors and shadows, and nothing tells you where to look for a given property.

Prettier doesn't sort classes

Prettier formats JavaScript, but it leaves Tailwind classes as they are. That makes sense, because Prettier doesn't know Tailwind's recommended class order.

The Tailwind team has a recommended order: layout first, then spacing, then colors and effects. You could remember it and follow it by hand, but you don't need to.

What the plugin does

prettier-plugin-tailwindcss knows Tailwind's class order and sorts your classes to match it.

Before the plugin runs:

<div className="bg-white px-6 pt-4 text-sm shadow-sm mt-2 mb-4 rounded-lg border">

After the plugin runs:

<div className="mt-2 mb-4 rounded-lg border bg-white px-6 pt-4 text-sm shadow-sm">

It's a small change. Layout and spacing come first, then visual styling. After a while you know where to look, and you read components faster.

Setup

Install the plugin:

npm install -D prettier prettier-plugin-tailwindcss 

Then add it to your Prettier config:

// your prettier.config file
module.exports = {
  plugins: ['prettier-plugin-tailwindcss'],
}

That's it. The next time you format your code (Cmd+S if you have format-on-save on), Prettier sorts your Tailwind classes in the recommended order. You don't need to configure anything.

Why I use it

The plugin removes one small decision from my work. I stop thinking about where a new hover: class goes, or whether mb-4 comes before or after px-6.

On a team, it helps more. Everyone's classes end up in the same order after formatting, so code reviews don't get stuck on class order.

If you already use Prettier (and you probably should), add this plugin. The official repository has more details, but honestly, the setup above is all most projects need.