How to overwrite tailwind class on old class like !important in css

516 views Asked by At

I used text-[20px] in <Badge/>, but it's overridden by another css class, how can I override tailwind the class

<Badge
  label="1"
  className='w-[30px] h-[30px] p-6 ml-4 text-[20px]'
  style={{ lineHeight: '20px'}}>
  1
</Badge>

3

There are 3 answers

0
Simon On BEST ANSWER

There are a number of ways to solve this problem. The simplest solution is to add a ! to the start of the class. Tailwind will make it important. This is similar to the above suggestion to add [&&]: to the start, which increases the specificity.

<Badge
  label="1"
  className='w-[30px] h-[30px] p-6 ml-4 !text-[20px]'
  style={{ lineHeight: '20px'}}>
  1
</Badge>

If you are able to edit the <Badge> component, there are a couple of other solutions that are a bit cleaner in that you don't need to add the variants in your pages, it's all handled by the component.

The tailwind-unimportant plugin for Tailwind solves this problem by adding a variant that reduces the specificity of the component classes so that they can be overridden.

// Add `-:` prefix in the badge component
const Badge = ({className, children}) => {
    className = '-:text-base ' + className;
    return <button class={className}>{ children }</button>
}

// The class without the `-:` will be applied
<Badge className="text-[20px]">1</Badge>

There's also the tailwind-merge, a JS library that will de-duplicate these clashing classes.

0
Hossein Azizdokht On

If you want to override the text-[20px] on other classes, you can write the class like this:

 <Badge
   label="1"
   className='w-[30px] h-[30px] p-6 ml-4 [&&]:text-[20px]'
   style={{ lineHeight: '20px'}}>
   1
 </Badge>

0
eYinka On

Another thing I found handy when dealing with situations like this is that using your own custom class could increase the specificity and override Tailwind's base styles.

In your case, you can define a class in your stylesheet like:

.badge-text {
 @apply text-[20px];
}

Then your template can go as:

<Badge
  label="1"
  className='w-[30px] h-[30px] p-6 ml-4 badge-text'
  style={{ lineHeight: '20px'}}>
  1
</Badge>

This has worked for me in many cases.