'TailwindCSS 3 classes doesn't override previous classes

I am facing an issue which is mind-numbing in the world of CSS. TailwindCSS 3 classes just doesn't override previous classes.

For example, there is this component, I created:

import * as React from "react";

const TextBox = ({ addClassName, children }) => {
  const className = `text-xl leading-7.5 font-lato font-normal ${addClassName}`;
  return <div className={className}>{children}</div>;
};

export default TextBox;

Then I go ahead and use this component above at another place, like this:

<TextBox addClassName="text-4xl">My New Text</TextBox>

Now when I inspect it in the browser, it shows both of the font-size: Screenshot from the browser inspect

class="text-xl leading-7.5 font-lato font-normal text-4xl"

As you can see both of the classes are there, both referring to font-size, and the larger one is after the smaller one.

And still ONLY the small ( the original ) font-size will be the dominant.

( as a side note, I did try to put the addClassName variable in the front as well, no help )

Why is this?

I appreciate any help getting with this. Thank you



Solution 1:[1]

I would suggest you to try clsx or clsssnames for better usage with tailwind classes instead of string interpolation

Solution 2:[2]

I found a Solution guys. Setup props with default CSS values at the original component, and then at the time of the usage of this aforementioned component, if we need different style, we just gave that in the props.

Solution 3:[3]

Quoting from redit

In CSS if you have two selectors with equal specificity the one that comes last in the CSS structure takes precedence. The order in the class attribute has no effect.

Suggested solution would be to write your own class after tailwindcss import statement, or edit it using inline style.

My personal tip: Don't use two classes that target the same css property, text-lg and text-4xg both target font-size, you need a way (suggest clsx lib) to put only one class name and not the other

import clsx from 'clsx';


let condition = false;

function Component(){


  return (
    <div>
     <p className={clsx({
       "text-lg": condition,
       "text-4xl": !condition,
     })}>
     ...
     </p>
    </div>
  );
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gokulprasanth
Solution 2 CsongorCzezar
Solution 3 Mhd Louay Al-osh