Sub topic 11
Merging and overriding classes safely
This chapter assumes you can write React components with props and JSX, and that you have read the earlier chapters on utility classes, conditional class names, and extracting components with typed variants. You should also be comfortable with TypeScript function signatures.
By the end, you will know why two conflicting Tailwind classes on one element do not resolve the way you expect. You will also know how clsx and tailwind-merge fix that, and where the combination still goes wrong.
The problem: class order in the string does not matter
When a reusable component sets p-4 internally and a caller passes p-8 through className, you might expect the later class to win. It does not, because CSS does not look at the order of names in the class attribute. It looks at the order of rules in the generated stylesheet.
Tailwind emits its utilities in a fixed order that it controls. For two utilities that set the same property at the same specificity, the one defined later in the stylesheet wins, regardless of which one you wrote last in the HTML.
export function Box({ className }: { className?: string }) {
// The caller's class is appended last, but that does not make it win.
return <div className={`p-4 ${className ?? ''}`}>Content</div>
}
// Renders class="p-4 p-8". Which padding applies depends on stylesheet order.
export const example = <Box className="p-8" />For p-4 and p-8, the generated CSS happens to define the larger spacing value later, so p-8 wins here. Try the same with p-8 internally and p-4 from the caller. The caller's class loses, because p-8 is still later in the stylesheet. The outcome depends on stylesheet order, not on intent.
Two separate jobs
Two small libraries solve two different problems, and it helps to keep them apart.
| Library | Job | Example |
|---|---|---|
| `clsx` | Build one class string from strings, arrays, objects, and falsy values | `clsx('a', cond && 'b')` gives `'a b'` or `'a'` |
| `tailwind-merge` | Remove earlier Tailwind classes that conflict with later ones | `twMerge('p-4 p-8')` gives `'p-8'` |
clsx handles conditions. tailwind-merge handles conflicts. Neither does the other's job.
Install the libraries
Both packages are installed as regular dependencies.
npm install clsx tailwind-mergeThe `cn` helper
The standard pattern combines both into one function. This is the helper from the topic's code examples, saved as src/cn.ts.
import { clsx, type ClassValue } from 'clsx'
import { twMerge } from 'tailwind-merge'
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}The order of operations matters:
clsxflattens all inputs into one space-separated string. It dropsfalse,null,undefined,0-like falsy values, and empty strings.twMergereads that string from left to right and removes any class that a later class makes redundant.
The rule is simple: the last conflicting class wins, and the earlier one is removed from the output.
import { cn } from './cn'
cn('p-4', 'p-8') // 'p-8'
cn('px-2 py-1', 'p-4') // 'p-4'
cn('text-sm', false && 'text-lg') // 'text-sm'
cn('bg-red-500', { 'bg-blue-500': true }) // 'bg-blue-500'
cn('text-red-600', 'text-lg') // 'text-red-600 text-lg'The last line shows why the library needs to understand Tailwind. text-red-600 sets color and text-lg sets font size. Both start with text-, but they do not conflict, so both stay. A plain string comparison on prefixes would get this wrong.
What `tailwind-merge` understands
tailwind-merge has a built-in model of Tailwind's class groups. It knows which utilities write to the same CSS property and which utilities are shorthands for others.
- Same property:
p-4andp-8both set padding, so the later one wins. - Shorthand over longhand:
px-2 py-1followed byp-4leaves onlyp-4, becausep-4sets all four sides. - Longhand after shorthand is kept:
p-4 px-2stays as is.px-2refinesp-4for the horizontal sides, and the two do not cancel each other. - Variants are separate:
p-4 hover:p-8is unchanged, because the hover variant applies in a different state. Buthover:p-4 hover:p-8becomeshover:p-8. - Modifiers are compared as a set:
md:hover:p-4andhover:md:p-8count as the same variant combination. - Important and arbitrary values are handled:
p-[13px]conflicts withp-4, because both set padding.
A component that accepts overrides
Here is the typed Button from the previous chapter, using cn so that callers can override its defaults. The class order passed to cn is important: defaults first, variant second, caller's className last.
import { cn } from './cn'
const variants = {
primary: 'bg-blue-600 text-white hover:bg-blue-700',
secondary: 'bg-gray-100 text-gray-900 hover:bg-gray-200',
} as const
type ButtonProps = React.ButtonHTMLAttributes<HTMLButtonElement> & {
variant?: keyof typeof variants
}
export function Button({ variant = 'primary', className, ...props }: ButtonProps) {
return (
<button
className={cn(
'rounded-md px-4 py-2 font-medium disabled:opacity-50',
variants[variant],
className
)}
{...props}
/>
)
}A caller can now change the padding and the color safely:
import { Button } from './Button'
export function Toolbar() {
return (
<div className="flex gap-2">
<Button>Default</Button>
<Button className="px-8 py-3">Roomy</Button>
<Button variant="secondary" className="bg-emerald-600 text-white hover:bg-emerald-700">
Custom color
</Button>
</div>
)
}For the second button, cn receives px-4 py-2 and then px-8 py-3. The merge removes px-4 and py-2, so the rendered class list holds only one padding value per axis. For the third button, the variant's bg-gray-100, text-gray-900 and hover:bg-gray-200 are removed, and the caller's three classes replace them.
How the pieces fit together
Using `cn` for conditions
cn is also the right tool for conditional classes inside a component, not only for overrides. clsx accepts objects, where keys are classes and values are conditions.
import { cn } from './cn'
type TabProps = {
label: string
active: boolean
onSelect: () => void
}
export function Tab({ label, active, onSelect }: TabProps) {
return (
<button
onClick={onSelect}
className={cn(
'border-b-2 px-3 py-2 text-sm',
active
? 'border-blue-600 text-blue-700'
: 'border-transparent text-gray-600 hover:text-gray-900'
)}
>
{label}
</button>
)
}Here the two branches are complete class strings, so Tailwind can detect them, as covered in the chapters on class detection and dynamic class names. cn is not needed to resolve a conflict in this case, because only one branch is ever present. It still does no harm, and it keeps the call site consistent with the rest of your components.
Gotchas and failure modes
Custom theme tokens that the merger does not know
tailwind-merge ships with the default Tailwind scales. If you add a custom font size or color in @theme, the library may not know which group a new name belongs to. For colors, any text-<name> class is generally treated as a color. For other groups, such as a custom text size named text-huge, the merger can misread it as a color and let it conflict with text-red-600.
You fix this by extending the merger's configuration with extendTailwindMerge.
import { clsx, type ClassValue } from 'clsx'
import { extendTailwindMerge } from 'tailwind-merge'
const twMerge = extendTailwindMerge({
extend: {
classGroups: {
'font-size': [{ text: ['huge', 'tiny'] }],
},
},
})
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}Check the tailwind-merge documentation for the group names that match your installed version, since they have changed between major versions. Also check that your installed tailwind-merge major version supports Tailwind v4. Version 3 is the line built for Tailwind v4 class names, while version 2 targets Tailwind v3.
Merging only works on complete strings
twMerge compares class names as text. If a class is built from fragments, as in ` text-${color}-600 `, Tailwind cannot generate it, and the merger sees a string it may not recognize. Always pass complete class names, as shown in the dynamic classes chapter.
Component-level overrides hide design intent
Letting every caller override any class makes it easy to break the look of a design system. If a Button should only come in two colors, offer a variant prop and keep the override for spacing and layout. Allowing className on every component is a convenience, and it is a choice you make on purpose.
Cost on hot paths
twMerge parses every class string. It caches results, and it is fast enough for normal components. In a list that renders thousands of rows, call cn only where there is something to merge. For a fixed string with no conditions and no className prop, write the string directly.
Conflicts across non-class sources
The merger only sees what you pass it. Styles from a style prop, from a global stylesheet, or from @apply rules are outside its view. An inline style={{ padding: 8 }} beats any utility class regardless of merging.
When you do not need a merger
If a component never accepts a className prop and builds its classes from a closed set of variants, conflicts cannot occur, and clsx alone is enough. Adding twMerge becomes worthwhile once callers can pass arbitrary classes, or once you compose several class sources where a later one is meant to replace an earlier one.
| Situation | Use |
|---|---|
| Fixed classes, no conditions | A plain string |
| Conditions, no overriding | `clsx` |
| Caller `className` or overlapping sources | `cn` (`clsx` plus `twMerge`) |
| Custom theme tokens in merges | `cn` with `extendTailwindMerge` |
Checking your work
You can test cn like any pure function. A few assertions guard against regressions after you upgrade Tailwind or tailwind-merge.
import { describe, expect, it } from 'vitest'
import { cn } from './cn'
describe('cn', () => {
it('keeps the last conflicting class', () => {
expect(cn('p-4', 'p-8')).toBe('p-8')
})
it('keeps unrelated classes', () => {
expect(cn('text-red-600', 'text-lg')).toBe('text-red-600 text-lg')
})
it('treats variants separately', () => {
expect(cn('p-4', 'hover:p-8')).toBe('p-4 hover:p-8')
})
it('ignores falsy values', () => {
expect(cn('p-4', false, null, undefined, '')).toBe('p-4')
})
})Exercise
A component renders className={px-4 ${className}}. A caller passes className="px-8", and sometimes the padding stays at px-4-sized. Why can this happen, and what change makes the override reliable?
Show answer
The browser does not use the order of class names in the attribute. It uses the order of rules in the generated stylesheet, so the winner between px-4 and px-8 is decided by Tailwind's output order, not by which class comes last in the string. Replace the template string with cn('px-4', className). tailwind-merge then removes px-4 when the caller passes a conflicting padding class, so only one padding class reaches the element.
Exercise
What does cn('px-2 py-1', 'p-4', 'text-sm', 'text-gray-700', false) return, and why are text-sm and text-gray-700 both kept?
Show answer
It returns 'p-4 text-sm text-gray-700'. p-4 is a shorthand for all four sides, so it removes the earlier px-2 and py-1. text-sm sets font size and text-gray-700 sets color, which are different properties, so the merger keeps both. false is dropped by clsx.
Exercise
You add --text-huge: 4rem; to @theme and write cn('text-red-600', 'text-huge'). The red color disappears. What is the likely cause and the fix?
Show answer
tailwind-merge does not know that text-huge is a font size, so it can treat it as a text color and remove text-red-600 as a conflict. Extend the merger with extendTailwindMerge, registering huge in the font-size class group, and use that merger inside cn.