Merging conflicting classes with twMerge
twMerge joins Tailwind class strings and drops earlier classes that conflict with later ones, so an override such as p-3 replaces px-2 py-1.
How it works
- Call twMerge with several strings. Each row calls
twMerge(base, override)and prints the result. The first row is the example from the README. [1] - Default Tailwind config. No setup is needed:
twMergeis ready to use with Tailwind's default classes, somy-6replacesmt-2 mb-2here. [2] - Accepted arguments. Arguments can be strings, arrays or falsy values like
undefinedandfalse, which makes it easy to pass optional class props. [2]
Run and edit it
It runs in your browser, in a sandboxed frame that cannot see this site; the packages load from esm.sh only after you press Run.
import { twMerge } from "tailwind-merge";
// Later classes win when they set the same CSS property
const CASES = [
["px-2 py-1 bg-red hover:bg-dark-red", "p-3 bg-[#B91C1C]"],
["p-4 text-sm", "p-2"],
["text-red-500 font-bold", "text-blue-600"],
["mt-2 mb-2 rounded", "my-6"],
["rounded-lg shadow-sm", "rounded-none"],
];
export default function App() {
return (
<div style={page}>
<div style={card}>
<div style={{ color: "#a5b4fc", marginBottom: 12 }}>// twMerge(base, override)</div>
{CASES.map(([base, extra]) => (
<div key={base} style={{ marginBottom: 10 }}>
<div style={{ color: "#9ca3af" }}>twMerge("{base}", "{extra}")</div>
<div style={{ color: "#4ade80" }}>→ "{twMerge(base, extra)}"</div>
</div>
))}
</div>
</div>
);
}
const page = { minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center", background: "#111", fontFamily: "ui-monospace, Menlo, monospace" };
const card = { width: 540, padding: 20, borderRadius: 12, background: "#1b1b1f", border: "1px solid #2e2e35", color: "#e5e7eb", fontSize: 13 };
Each green line is the live output of twMerge; change a class in CASES to see a different merge. Code written by AgentGid [1].
Each green line is the live output of twMerge; change a class in CASES to see a different merge. Code written by AgentGid [1].Checked Oct 12, 2026: it starts without errors in Chromium with tailwind-merge 3.7.0, react 19.3.0, react-dom 19.3.0. Needs WebGL.
More Tailwind Merge examples
Conditional classes with twJoin Custom theme values in tailwind-merge Overriding component classes with twMerge Custom class groups in tailwind-merge
Sources
- Tailwind Merge README (GitHub)
- Docs: dcastil › tailwind-merge › blob › tailwind-merge@3.7.0 › packages › tailwind-mer
Explanations written by AgentGid from the official docs; the numbers in brackets point here. The code marked "written by AgentGid" is ours and free to copy.