@wuyuchentr/tailwind-merge-deep
v1.0.0
Published
Intelligently merge Tailwind CSS class strings, resolving conflicts like p-2 p-4 → p-4.
Maintainers
Readme
@wuyuchentr/tailwind-merge-deep
Intelligently merge Tailwind CSS class strings, automatically resolving conflicts like p-2 p-4 → p-4.
Why?
When you dynamically combine Tailwind classes, conflicting utilities (e.g., p-2 and p-4) both end up in the DOM. tailwind-merge-deep detects these conflicts and keeps only the last one, just like your CSS cascade would.
Install
npm install @wuyuchentr/tailwind-merge-deepUsage
import { merge } from '@wuyuchentr/tailwind-merge-deep';
// Basic
merge('p-2 p-4') // → 'p-4'
merge('text-red-500 text-blue-300') // → 'text-blue-300'
// Conflicting utilities
merge('p-2', 'p-4') // → 'p-4'
merge('p-2 m-2', 'p-4 m-4') // → 'p-4 m-4'
merge('px-2 py-4', 'p-6') // → 'p-6'
// Non-conflicting utilities are preserved
merge('p-2 text-red-500') // → 'p-2 text-red-500'
// With variants
merge('hover:p-2', 'hover:p-4') // → 'hover:p-4'
merge('p-2', 'hover:p-4') // → 'p-2 hover:p-4'
// Multi-variant
merge('dark:md:hover:p-2', 'dark:md:hover:p-4') // → 'dark:md:hover:p-4'
// Important modifier (!)
merge('!p-2', 'p-4') // → '!p-2 p-4' (different conflict keys)
// Multiple arguments
merge('p-2 m-2', 'p-4', 'm-4') // → 'p-4 m-4'
// Array support
merge('p-2', ['p-4', 'm-2']) // → 'p-4 m-2'
// Falsy values are ignored
merge('p-2', false && 'p-4') // → 'p-2'How it works
- Parses each class into
{ variant, body, important } - Matches the body against Tailwind utility groups (padding, margin, color, etc.)
- Classes in the same conflict group with the same variant prefix overwrite earlier ones
- Non-Tailwind classes (custom classes) are preserved as-is
Coverage
tailwind-merge-deep covers all major Tailwind utility categories:
- Layout: display, position, inset, overflow, float, etc.
- Sizing: width, height, min/max variants
- Spacing: padding, margin, space, gap
- Typography: font-size, font-weight, font-family, text-color, line-height, letter-spacing, text-align, etc.
- Background: bg-color, bg-image, gradient, etc.
- Borders: border-width, border-color, border-radius, border-style, divide
- Effects: shadow, opacity, ring
- Flex/Grid: all flex and grid utilities
- Transform: scale, rotate, translate, skew
- Transition: transition, duration, ease, delay, animate
- Others: cursor, outline, SVG (fill/stroke), and more
Not covered yet (contributions welcome):
aspect-ratiobackdrop-*filtersfilter/backdrop-filterscroll-*behaviorcolumns
API
merge(...classes: (string | false | null | undefined | string[])[]): stringAccepts any number of strings, arrays, or falsy values (which are ignored).
