Tailwind CSS: my class names are getting extremely long — is that normal?
poze 4 months ago615 gadeen
Some of my buttons have 20+ utility classes. It feels messy. Should I use @apply everywhere?
Dyagnostik IA
Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.
1 Repons
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.
Konekte pou di lòt moun si li te mache.
Sign in and verify your email to post an answer.