Search code examples
csstailwind-cssreact-bootstraptailwind-ui

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


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>


Solution

  • 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.