Search code examples
tailwind-css

Tailwind modifier syntax for multiple condidtions


If I want a an HTML link to be styled when it has a class name of "active" OR in the hover state, how do I do it with Tailwind CSS?

I've tried the following but it doesn't work when trying to set the font to semibold:

<a href="#" class="active [&.active]:hover:font-semibold"

(The active class is set by the web framework).


Solution

  • You could split the variants into two separate classes:

    tailwind.config = {
      theme: {
        extend: {
          fontFamily: {
            sans: ['Roboto', ...tailwind.defaultTheme.fontFamily.sans],
          }
        },
      },
    };
    <script src="https://cdn.tailwindcss.com/3.4.1"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;600&display=swap" rel="stylesheet">
    
    <a href="#" class="active [&.active]:font-semibold hover:font-semibold">
      Foo
    </a>
    <a href="#" class="[&.active]:font-semibold hover:font-semibold">
      Bar
    </a>

    Otherwise, if you wanted to stick to only one Tailwind class, you could use :is() or :where() in an arbitrary variant:

    tailwind.config = {
      theme: {
        extend: {
          fontFamily: {
            sans: ['Roboto', ...tailwind.defaultTheme.fontFamily.sans],
          }
        },
      },
    };
    <script src="https://cdn.tailwindcss.com/3.4.1"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;600&display=swap" rel="stylesheet">
    
    <a href="#" class="active [&:is(.active,:hover)]:font-semibold">
      Foo
    </a>
    <a href="#" class="[&:is(.active,:hover)]:font-semibold">
      Bar
    </a>
    
    <a href="#" class="active [&:where(.active,:hover)]:font-semibold">
      Foo
    </a>
    <a href="#" class="[&:where(.active,:hover)]:font-semibold">
      Bar
    </a>