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

Raycast: Supercharged productivity

Raycast is the one tool that stands behind its words, as it promises a "Supercharged" productivity and it surely delivers!


Tailwind Automatic Class Sorting with Prettier

Did you know that Tailwind has a Prettier plugin to bring order to your JSX and SCSS files? :D Now you do!