Tailwind Merge: clean your code by removing conflicting styling
Managing CSS styles efficiently can be a challenge, especially in projects that use Tailwind, where the nature of utility classes is to have quite a bunch of them together — inevitably having some overlap when inheriting styling from different sources.
The tailwind-merge
npm package (Opens in a new tab) by Dany Castillo (Opens in a new tab) offers a solution that combines and reuses Tailwind utility classes.
From their documentation we have the following example
1import { twMerge } from 'tailwind-merge' 2 3twMerge('px-2 py-1 bg-red hover:bg-dark-red', 'p-3 bg-[#B91C1C]') 4// → 'hover:bg-dark-red p-3 bg-[#B91C1C]'
that shows how Tailwind Merge combines the classes px-2 py-1
with p-3
and results in an overall cleaner list of classes, and explains in extremely simple terms the core of Tailwind Merge. There are more examples available in the tailwind-merge
npm package (Opens in a new tab) by Dany Castillo (Opens in a new tab) When and how to use it documentation page in Tailwind Merge GitHub repository (Opens in a new tab).
It's probably not the easiest to implement in an already-existing project, and the author also puts a lot of cases in favour and against using it. The readme section in GitHub of tailwind-merge
(Opens in a new tab) contains all the information you'll need to weight in whether it's going to be the solution you were looking for in your project, or if you should approach your issues from a different perspective.
I'd personally try to use it from the get-go, as implementing it in an already-existing project would require some refactoring that might or might not be time-consuming, but it's completely harmless to have it and update its usage progressively!