Tailwind CSS Best Practices for Large Projects #20304
Replies: 2 comments 1 reply
-
|
I work on a fairly large Tailwind v4 app (a few hundred components), and these are the things that actually kept it readable for us: 1. Let a formatter own the class order. Install the official Prettier plugin ( 2. Extract components, not classes. When the same class combo shows up in three places, make it a component (React, Vue, Blade, whatever you use) rather than reaching for 3. Put design decisions in the theme, not in arbitrary values. In v4 that means defining tokens with 4. Use a small helper for conditional classes. <button
className={clsx(
"flex items-center gap-2 rounded-lg px-3 py-2",
active && "bg-blue-600 text-white",
disabled && "pointer-events-none opacity-50",
)}
/>Base classes on one line, each condition on its own line. Much easier to read than template-string soup. 5. For components with lots of variants, use CVA. And one mindset thing: accept long class lists on leaf elements. A 15-class div is fine. The styles are colocated and greppable, which is the whole point of Tailwind. The goal isn't short attribute strings, it's zero duplication and consistent ordering. |
Beta Was this translation helpful? Give feedback.
-
|
a few things that have worked well at scale. first, keep component files small enough that the class list is readable at a glance. if a component jsx is over 100 lines, extract smaller pieces. long class strings are a symptom of a component doing too much, not a tailwind problem. second, use the import { clsx } from "clsx";
import { twMerge } from "tailwind-merge";
export const cn = (...args) => twMerge(clsx(args));this handles conflicts like third, extract repeated class groups into component variants using const button = cva("rounded px-4 py-2 font-medium", {
variants: {
intent: { primary: "bg-blue-500 text-white", ghost: "bg-transparent" }
}
});fourth, never sort classes manually. use prettier-plugin-tailwindcss. it enforces a consistent order automatically and removes the debate from code review. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
How do you organize Tailwind CSS classes in large projects to keep the code readable?
Beta Was this translation helpful? Give feedback.
All reactions