skip to Main Content

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


  1. 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:

    .text-blue-600 {
        color: blue; /* example */
    }
    .text-red-800 {
        color: red; /* example */
    }
    

    So if an element will have both the text-blue-600 and the text-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 the className property of your html/jsx so that the classes applied first are first in the string.

    Example of prettier-plugin-tailwindcss use:

    function App() {
        return (
            <div className="text-red-800 text-blue-600">
                Hello world
            </div>
        );
    }
    

    is automatically formatted to

    function App() {
        return (
            <div className="text-blue-600 text-red-800">
                Hello world
            </div>
        );
    }
    
    Login or Signup to reply.
  2. 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 precedence

    You example would become:

    function App() {
        const color = "text-blue-600";
        return (
            <div>
                <div className={`!text-red-800 ${color}`}>
                    hello
                </div>
                <div className={`-:text-red-800 ${color}`}>
                    world
                </div>
            </div>
        );
    }
    

    The -:text-red-800 class is always overridden by the text-blue-600 class without the -: variant, and the text-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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search