Merge Tailwind CSS classes without style conflicts
open sourceMITself-hostablefree
tailwind-merge is a JavaScript utility, twMerge, that joins Tailwind CSS class strings and removes the ones that conflict, so the last conflicting class wins: twMerge('px-2 py-1 bg-red', 'p-3 bg-[#B91C1C]') keeps only p-3 bg-[#B91C1C]. It understands modifiers and stacked variants, arbitrary values, properties and variants, the important modifier and custom colours, keeps classes that aren't Tailwind's, accepts conditional classes and arrays, and caches results. It's typically used when a component accepts a className prop that should override its own classes. Version 3 supports Tailwind CSS v4.0 to v4.3, with v2.6.0 for Tailwind v3; it can be configured or extended with plugins for custom themes, is fully typed and MIT-licensed, and is made by Dany Castillo.
Problems it solves
- when I pass a className to my React component its Tailwind classes clash with the component's defaults
- p-3 and px-2 both end up on the element and the wrong padding wins
- let callers override a component's background or spacing classes without a pile of conditionals
- combine conditional Tailwind classes and drop the ones that conflict
- dedupe Tailwind classes with hover: and md: modifiers correctly
- merge Tailwind classes that use arbitrary values like bg-[#B91C1C]
- teach a class merging utility about the custom scales in my Tailwind theme
Features
- last conflicting class wins, including non-trivial conflicts between shorthand and longhand utilities
- modifiers, stacked modifiers, postfix modifiers and the important modifier
- arbitrary values (with type detection), arbitrary properties and arbitrary variants
- keeps non-Tailwind classes and supports custom colours out of the box
- multiple arguments, conditional classes and nested arrays
- cached results, reused data structures and lazy initialisation
- configuration and plugins for custom Tailwind themes
- fully typed
- supports Tailwind CSS v4.0 to v4.3; v2.6.0 for Tailwind v3
Limitations
- Doesn't tell custom classes apart from Tailwind ones that look the same: a custom text-2xs is merged as a font size1
Capabilities
| Takes plugins | plan not known |
|---|
