Search code examples
csstailwind-css

Tailwind set `group-hover` on button only when enabled


I have some buttons styled with TailwindCSS.

These buttons contains some icons / helper text (<span>) that should receive a color (different than the color used for button text) when the mouse is over the button.

I used the group class on button, and then in the inner element:

<script src="https://cdn.tailwindcss.com#.js"></script>

<button class="group bg-indigo-500 hover:enabled:bg-indigo-400 disabled:cursor-not-allowed">
  <span class="group-hover:text-pink-900">helper text</span>
</button>

<button disabled class="group bg-indigo-500 hover:enabled:bg-indigo-400 disabled:cursor-not-allowed">
  <span class="group-hover:text-pink-900">helper text</span>
</button>

Notifce that the hover effect is set only when the button is enabled (by using hover:enabled).

If the button is disabled, I want to disable this hover effect on the helper text well.

I've tried group-hover:enabled:text-pink-900, but it does not work.

disabled:pointer-events-none is not an option for me, because it will break disabled:cursor-not-allowed.

Example: https://play.tailwindcss.com/US7h6jStv9


Solution

  • I've managed to get the desired behaviour by combining group-* modifiers like this:

    group-hover:group-enabled:...

    <span class="group-hover:group-enabled:text-pink-900">★</span>
    

    <script src="https://cdn.tailwindcss.com#.js"></script>
    
    <button class="group bg-indigo-500 hover:enabled:bg-indigo-400 disabled:cursor-not-allowed ...">
      Button text
      <span class="group-hover:group-enabled:text-pink-900">★</span>
    </button>
    
    <button disabled class="group bg-indigo-500 hover:enabled:bg-indigo-400 disabled:cursor-not-allowed ...">
      Button text
      <span class="group-hover:group-enabled:text-pink-900">★</span>
    </button>

    Explanation:

    • group-hover:group-enabled:text-indigo-900 => produces the following css rule:
    .group:hover:enabled .(classname) {
      --tw-text-opacity: 1;
      color: rgb(131 24 67 / var(--tw-text-opacity));
    }
    

    Example: https://play.tailwindcss.com/6BmIcNS610