Tailwind CSS: my class names are getting extremely long — is that normal?
asked 4 months ago617 viewsen
Some of my buttons have 20+ utility classes. It feels messy. Should I use @apply everywhere?
AI diagnosis
AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.
1 Answer
Long class lists are normal in Tailwind. The tool's answer to duplication is components, not @apply:
const variants = {
primary: 'bg-blue-700 text-white hover:bg-blue-800',
ghost: 'bg-transparent hover:bg-gray-100',
};
export function Button({ variant = 'primary', className, ...props }) {
return (
<button
className={cn(
'inline-flex items-center gap-2 rounded-md px-4 py-2 text-sm font-medium',
'focus-visible:outline-2 focus-visible:outline-offset-2 disabled:opacity-50',
variants[variant],
className,
)}
{...props}
/>
);
}
- cn = clsx + tailwind-merge, which resolves conflicting classes when you override with className. - For many variants, class-variance-authority (cva) structures this cleanly. - @apply is fine for a few spots you can't componentize (third-party markup, markdown content), but overusing it just recreates traditional CSS with extra steps. - The Prettier Tailwind plugin sorts classes so long lists stay readable.
Sign in to tell others whether this worked.
Sign in and verify your email to post an answer.