Sub topic 6
Merging classes and resolving conflicts
This chapter assumes you can read Tailwind utility classes, know how a React (or similar) component accepts props, and understand the basic CSS cascade. You should also have seen the Button component with a variants map from the previous chapter. Here you will see what goes wrong when a component lets callers add their own classes, and how to fix it.
The problem: class order in HTML does not decide the winner
A reusable component usually accepts a className prop so that callers can adjust spacing, width, or color for one use. The obvious implementation concatenates strings:
const variants = {
primary: "bg-blue-600 text-white hover:bg-blue-700",
secondary: "bg-gray-200 text-gray-900 hover:bg-gray-300",
};
export function Button({ variant = "primary", className = "", children, ...props }) {
return (
<button
className={`rounded-md px-4 py-2 font-semibold ${variants[variant]} ${className}`}
{...props}
>
{children}
</button>
);
}A caller then writes <Button className="px-8">Save</Button>. The rendered element has this class attribute:
<button class="rounded-md px-4 py-2 font-semibold bg-blue-600 text-white hover:bg-blue-700 px-8">Save</button>The element now carries both px-4 and px-8. Which one applies?
The order of class names inside the class attribute does not matter to CSS. What matters is the order of the rules in the generated stylesheet. For two selectors with equal specificity, such as .px-4 and .px-8, the rule that appears later in the stylesheet wins. Tailwind decides the order of its rules, not you. In general it sorts utilities so that properties that cover more (like p-4) come before properties that cover less (like px-4), and within the same property it orders by value. So px-8 and px-4 may give a result you expect, but px-4 and px-2 may not: the winner depends on where Tailwind placed each rule, not on which one you wrote last.
This means that an override passed through className is unreliable. It works in some cases and silently fails in others.
Conflicts you can spot
A conflict exists when two classes set the same CSS property for the same state. These are examples:
| Classes on one element | Conflict? | Why |
|---|---|---|
| `px-4 px-8` | Yes | Both set horizontal padding |
| `px-2 p-3` | Yes | `p-3` includes horizontal padding |
| `text-sm text-lg` | Yes | Both set font size |
| `text-white text-lg` | No | One sets color, the other font size |
| `bg-blue-600 hover:bg-blue-700` | No | Different states (`hover:` is a different variant) |
| `bg-blue-600 bg-red-500` | Yes | Both set background color |
| `md:px-4 md:px-8` | Yes | Same variant, same property |
The text-white text-lg row is worth noticing. Both start with text-, but one is a color and one is a size. Any tool that resolves conflicts needs to understand Tailwind's class names, not just their prefixes.
Merging with tailwind-merge
tailwind-merge is a JavaScript library that takes a list of Tailwind classes and removes the ones that are overridden by a later class. It knows which utilities set the same property, and it knows about variants and shorthand relationships such as p-3 covering px-2 and py-1.
import { twMerge } from "tailwind-merge";
twMerge("px-2 py-1", "p-3"); // "p-3"The later argument wins. p-3 replaces both px-2 and py-1, because it sets all four sides of padding. The result is one class instead of three, and no ambiguity remains.
Some more cases show how it behaves:
import { twMerge } from "tailwind-merge";
console.log(twMerge("px-4 py-2", "px-8"));
// "py-2 px-8"
console.log(twMerge("text-white text-lg", "text-sm"));
// "text-white text-sm"
console.log(twMerge("bg-blue-600 hover:bg-blue-700", "bg-red-500"));
// "hover:bg-blue-700 bg-red-500"
console.log(twMerge("p-3", "px-2"));
// "p-3 px-2"Check each result against the rules:
px-4 py-2pluspx-8: only the horizontal padding conflicts, sopx-4is dropped andpy-2stays.text-white text-lgplustext-sm: the library separates color from size. Onlytext-lgis dropped.bg-blue-600 hover:bg-blue-700plusbg-red-500: the plain background is replaced. Thehover:class is kept, because it applies to a different state.p-3pluspx-2: both are kept. The later class is more specific about the sides it covers, so it does not makep-3redundant. The final padding is still decided by the stylesheet order, and Tailwind placespx-*afterp-*, so the result is what you expect.
The last case shows the rule: tailwind-merge removes a class only when a later class fully overrides it. It does not remove a class that still contributes something.
Combining with conditional classes: the cn helper
In practice you also want to build class lists conditionally. The clsx library does that: it accepts strings, objects, and arrays and returns one string, skipping falsy values. The common pattern is to wrap both libraries in one helper, usually called cn:
import { clsx } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs) {
return twMerge(clsx(inputs));
}clsx flattens and filters, then twMerge resolves conflicts in the resulting string. Now the button from the start of this chapter can be written safely:
import { cn } from "./cn";
const variants = {
primary: "bg-blue-600 text-white hover:bg-blue-700",
secondary: "bg-gray-200 text-gray-900 hover:bg-gray-300",
};
export function Button({ variant = "primary", className, children, ...props }) {
return (
<button
className={cn(
"rounded-md px-4 py-2 font-semibold",
variants[variant],
className
)}
{...props}
>
{children}
</button>
);
}Now <Button className="px-8">Save</Button> produces a class list in which px-4 has been removed. The caller's class is the only horizontal padding left, so the stylesheet order no longer matters.
The order of arguments in cn carries the meaning: defaults first, caller overrides last. If you reverse them, the component's own defaults would beat the caller's classes.
Edge cases and limits
Merging happens at runtime
twMerge runs in the browser (or on the server) each time the component renders. It caches results, so repeated calls with the same input are cheap, but it is still extra work and extra bundle size. For a handful of components this is negligible. For thousands of elements rendered in a tight loop, measure first.
It only sees class strings it can read
tailwind-merge works on the string it receives. It cannot see CSS you wrote by hand, and it cannot merge classes that were never part of the string. If a stylesheet defines .btn-primary with @apply px-4, then cn("btn-primary", "px-8") leaves both classes. The library does not know what .btn-primary contains, so it cannot tell that there is a conflict. In that case the stylesheet order decides, which is the unreliable situation this chapter started with.
Custom theme values need configuration
The library ships with knowledge of Tailwind's default class names. If your project adds custom utilities, for example a font size called text-huge, the library may treat text-huge as a color and fail to remove a conflicting text-lg. You can extend its configuration with extendTailwindMerge so it learns your names. Test a few of your own classes after any theme extension.
The important modifier
A class with the important modifier, such as px-4!, has a different effect from the same class without it. tailwind-merge treats them as separate. twMerge("px-4!", "px-8") keeps both. Prefer to avoid the modifier in components that accept overrides.
Dynamic class names still break detection
Merging does not change the rule from the earlier chapter: Tailwind finds classes by scanning your source for complete strings. The following code does not work, because px-${size} never appears as a whole class name:
// Broken: Tailwind cannot detect "px-4" or "px-8" in this source.
const padding = `px-${size}`;Write the whole names in a map, as with variants, and pass the selected value into cn.
When to use merging
Use cn with twMerge when:
- A component accepts a
classNameprop and callers may override defaults. - A variant and a conditional state could set the same property.
- You compose components inside other components, so classes pass through several layers.
You do not need it when a component accepts no className and every variant sets a distinct set of properties. In that case plain string joining is enough, and you avoid the dependency.
An alternative to merging is to avoid conflicts by design: expose explicit props such as size or fullWidth and keep className for rare cases. This is more work up front, but the component's contract is clearer and nothing has to be resolved at runtime.
Summary of the working model
- Two utilities conflict when they set the same property in the same variant state.
- The browser picks the winner by stylesheet order, which Tailwind controls and the
classattribute does not. twMergeremoves earlier classes that a later class fully overrides.clsxhandles conditional input, andcncombines both.- Merging only works on class strings it can see, so it does not resolve conflicts with hand-written CSS or
@applyclasses.
Exercise
A component renders cn("rounded-md px-4 py-2 bg-blue-600", className). A caller passes className="px-8 bg-red-500 hover:bg-red-600". Write the class list that twMerge returns, and explain why py-2 and rounded-md survive. Then say what would happen if the arguments were reversed.
Show answer
The result is rounded-md py-2 px-8 bg-red-500 hover:bg-red-600. px-4 is removed because px-8 sets the same property, and bg-blue-600 is removed because bg-red-500 sets the same property. py-2 (vertical padding) and rounded-md (border radius) set properties that the caller's classes do not touch, so they stay. The hover:bg-red-600 class has no conflict because the base had no hover class. If the arguments were reversed, the caller's classes would come first and the component's defaults would win, so px-4 and bg-blue-600 would be kept and the overrides would be dropped.
Exercise
A project defines .btn-primary { @apply px-4 py-2; } in its CSS. A component renders cn("btn-primary", "px-8"). Does twMerge resolve the padding conflict? What decides the final padding, and what are two ways to fix it?
Show answer
No. twMerge only sees the class names btn-primary and px-8, and it does not know that btn-primary contains padding, so it keeps both. The final padding is decided by the order of the two rules in the generated stylesheet, which makes the override unreliable. Two fixes: write the base padding as utilities in the component (cn("px-4 py-2", className)) so twMerge can see them, or move the padding out of .btn-primary and apply it through a prop or a separate class so no override is needed.