In this code below, I have 2 divs. From what I expect, we should have "hello" in red and "world" in blue. but both of them are in red. I could not figure out why. A solution for that can be using tailwind-merge library, but I still want to understand what is happening here. Thanks a lot.
function App() {
const color = "text-blue-600";
return (
<div>
<div className={`${color} text-red-800`}>
hello
</div>
<div className={`text-red-800 ${color}`}>
world
</div>
</div>
);
}
2
Answers
The thing is that the final result only depends on the order of the css classes in the file created by TailwindCSS for applying them. In this case, the result css file, will be something like:
So if an element will have both the
text-blue-600
and thetext-red-800
classes, only the last one in the returned css file will be applied.You can understand more of this and avoid these errors with
prettier-plugin-tailwindcss
that automatically formats theclassName
property of yourhtml
/jsx
so that the classes applied first are first in the string.Example of
prettier-plugin-tailwindcss
use:is automatically formatted to
An alternative solution to tailwind-merge is to use the tailwindcss-unimportant plugin for Tailwind. It adds a variant,
-:
, that let you make classes with lower specificity, meaning they can be overridden.Tailwind also has an important prefix,
!
, that can make classes have a higher precedenceYou example would become:
The
-:text-red-800
class is always overridden by thetext-blue-600
class without the-:
variant, and thetext-blue-600
class is always overridden by the!text-red-800
class with the important prefix.Note, as per the other answer, the order of the classes does not matter so I’ve rearranged them in this example.