Which bg color should be apply, when multiply bg-color class was appled to the same element? #12733
-
env
for example: <button className="bg-orange-400 bg-red-400 bg-teal-100 bg-teal-400 bg-red-100 bg-violet-400 p-4">my-btn</button> now chrome render a button with bg-red-100 background color. Can somebody tell me, what is the priority of bg color ? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
I don't have the direct answer to your question but I don't think it should matter in this context. That is to say, one should not be applying more than one class name that applies the same CSS property with the same variant(s). |
Beta Was this translation helpful? Give feedback.
-
Hey @wu67! When multiple classes are set on the same element, the browser applies the latest one found in the code, which in this case is "Violet". While Tailwind CSS does not guarantee the order of class generation, it maintains a fairly consistent order. However, during development, the order may change frequently because it only adds the latest updates to the end of the file instead of fully regenerating it with every change. This is why you may observe the latest class you added taking priority in development, but getting different results in the production build. To avoid this issue, it's best to avoid applying the same style classes (like "background") to the same element. One way to handle this is by using the Tailwind Merge utility. This utility analyzes your class name string and removes all duplications, keeping only the last appearance. Here's an example: const Button = ({ className }) => <button className={twMerge("bg-red-500", className)}>...</button>
...
// Button with red background
<Button />
// Button with blue background
<Button className="bg-blue-500" /> Hope this helps! |
Beta Was this translation helpful? Give feedback.
-
@wongjn @alex-krasikau <div className={classnames(
'some-class-here', {
'class-a': foo > 2.5,
'class-b': foo > 3,
...
}
)}></div> In the code , the Now i try to use another function, like this: calcSomeClass(val) {
if (val > 3) {
return 'class-b'
} else if (val > 2.5) {
return 'class-a'
} else {
// other
}
} <div className={classnames(
'some-class-here',
calcSomeClass(foo),
...
)}></div> I think it is easy enough to avoid this problem without another npm package. |
Beta Was this translation helpful? Give feedback.
What you've written is correct. You can use different options such as if statements, the ternary operator, or clsx to choose from multiple variants of the same class. In this case, there is only one class of that kind in the resulting class name string.
To ensure predictable behavior, the resulting class string should only have one class of its kind. It can also have other classes when using modifiers.
Examples: