Search code examples
csscss-selectorstailwind-css

How to chain data attribute and disabled selector in tailwind?


I have an button with data-loading=true and disabled attributes. I need to write a style in tailwind that applies only if data-loading!=true and disabled.

<button data-loading='true' disabled>Submit</button>

Tried (not working)

disabled:not(data-[loading=true]):bg-red

Solution

  • You can use the disabled: variant for when an element would match the :disabled pseudo-class.

    For when data-loading is not the value of true, you can use an arbitrary variant with :not() and an attribute selector: [&:not([data-loading=true])]:.

    To combine these two, you can chain them separately:

    <script src="https://cdn.tailwindcss.com/3.3.5"></script>
    
    <button data-loading='true' disabled class="[&:not([data-loading=true])]:disabled:bg-red-500">Submit</button>
    <button data-loading='false' disabled class="[&:not([data-loading=true])]:disabled:bg-red-500">Submit</button>

    Or you can have the :disabled pseudo class in the arbitrary variant instead of the built-in variant:

    <script src="https://cdn.tailwindcss.com/3.3.5"></script>
    
    <button data-loading='true' disabled class="[&:not([data-loading=true]):disabled]:bg-red-500">Submit</button>
    <button data-loading='false' disabled class="[&:not([data-loading=true]):disabled]:bg-red-500">Submit</button>