Tailwind CSS: my class names are getting extremely long — is that normal?

posée 4 months ago620 vuesen

7

Some of my buttons have 20+ utility classes. It feels messy. Should I use @apply everywhere?

Diagnostic IA

Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.

posée 4 months ago

1 réponse

7
✓
✓ Réponse acceptée

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.

Connectez-vous pour dire si ça a marché.

answered 4 months ago

Sign in and verify your email to post an answer.