Tailwind CSS Course
Tailwind CSS
/
Advanced

tailwind-merge

Definition

A utility function to elegantly merge Tailwind CSS classes in JS without style conflicts.

Explain Like I'm New

If a Button component has `p-4` as its default class, but you pass `className="p-8"` as a prop, standard string concatenation results in `class="p-4 p-8"`. The browser gets confused about which padding to apply. `tailwind-merge` intelligently analyzes the string, realizes they conflict, and automatically deletes `p-4`.

Real World Example

Building highly reusable React components where the developer consuming the component needs the ability to safely override the default Tailwind styles.

Common Use Cases

  • Component library development
  • React prop merging

Interactive Example

import { twMerge } from 'tailwind-merge';

// ❌ BAD: Simple String Concatenation
// Result: "px-4 py-2 bg-blue-500 bg-red-500"
// The browser is confused. The button might stay blue!
function BadButton({ className }) {
  return <button className={`px-4 py-2 bg-blue-500 ${className}`}>Click</button>
}

// ✅ GOOD: Using tailwind-merge
// Result: "px-4 py-2 bg-red-500" (It intelligently deleted bg-blue-500!)
function GoodButton({ className }) {
  return <button className={twMerge('px-4 py-2 bg-blue-500', className)}>Click</button>
}

// Usage:
<GoodButton className="bg-red-500" />

Interview Questions

basic

  • If you concatenate the string `"bg-red-500 bg-blue-500"`, which color will the browser actually display?

intermediate

  • What is the difference between the `clsx` package and `tailwind-merge`?

Flash Cards

Question

Which color?

Click to reveal answer
Answer

It depends entirely on the order those classes appear in the generated CSS file, NOT the order they appear in the HTML string. This is why class conflicts are so dangerous and unpredictable without `tailwind-merge`.

Question

clsx vs tailwind-merge?

Click to reveal answer
Answer

`clsx` simply joins strings together with spaces conditionally. It does not understand Tailwind CSS. `tailwind-merge` actively parses the Tailwind utility meanings and removes conflicting classes.