Search code examples
htmlcsstailwind-css

How to access all the children of a div in Tailwind CSS with hover event?


I have a nav bar like this:

<nav class="space-x-4">
  <router-link to="/home" class="hover:text-gray-300 transition duration-300">Home</router-link>
  <router-link to="/form" class="hover:text-gray-300 transition duration-300">Form</router-link>
  <router-link to="/about" class="hover:text-gray-300 transition duration-300">About</router-link>
</nav>

But I'd like to avoid the class duplication, so I tried the syntax mentioned in this post:

<nav class="space-x-4 [&>router-link]:hover:text-gray-300 transition duration-300">
  <router-link to="/home">Home</router-link>
  <router-link to="/form">Form</router-link>
  <router-link to="/about">About</router-link>
</nav>

It works well, except that when I hover one element, it highlights all elements. It appears that grouping the class this way is also grouping the event handling.

I've got exactly 1 hour experience on Tailwind, so sorry in advance if I missed this point on the docs, but I didn't find anything about my issue.


Solution

  • To do exactly what you want to do with inline css and tailwind classes, you just need to modify your code slightly. Here's how:

    <nav class="space-x-4 hover:[&>a]:text-gray-300 transition duration-300">
      <router-link to="/home">Home</router-link>
      <router-link to="/form">Form</router-link>
      <router-link to="/about">About</router-link>
    </nav>
    

    You can swap [&>a] for [&>router-link], if that works for you.