Tailwind Merge: clean your code by removing conflicting styling

Published on

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 by Dany Castillo 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 by Dany Castillo When and how to use it documentation page in Tailwind Merge GitHub repository.

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 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!




More Snippets

Unknown at rule @apply... k thx bye!

Are we finally done seeing all those "Unknown at rule @apply"?! Because I surely am!

139

declare-ai.org - ... so, who wrote that?!

Let everyone know how AI helped you... or didn't!

68