galdin
galdin

Reputation: 14074

Apply style on parent when hovering over a specific child element using tailwind

I have something like this:

<main id="parent" class="h-screen flex justify-center items-center">
  
  <div id="child" class="bg-red-200 w-96 h-72 flex">
  </div>
  
</main>

How would I go about applying .bg-blue-100 to the #parent only when hovering over #child?

(I understand that the opposite could be achieved using group on the parent, and group-hover on the child.)

Upvotes: 14

Views: 20852

Answers (3)

SethWhite
SethWhite

Reputation: 1977

With the latest tailwind, you can achieve this with unique group names: https://tailwindcss.com/docs/hover-focus-and-other-states#differentiating-nested-groups

If there are multiple iterations with the unique group name, only the currently hovered group will be affected.

<tr 
     v-for="song of songs"
     :key="song.id"
     class="group/row"
>
    <td class="group-hover/row:bg-zinc-900">{{ song.name }}</td>
</tr>

Upvotes: 0

Lo&#239;c V
Lo&#239;c V

Reputation: 635

In case you also want to style the parent whenever the child is focused, just add

"focus-within:bg-indigo-500"

(Obviously replacing "bg-indigo-500" by your style)

This would work when it happens for every child or if you only have one tho.

Upvotes: 14

JHeth
JHeth

Reputation: 8396

You can give the parent pointer-events-none and the child pointer-events-auto then apply hover:bg-100 or whatever hover effect to the parent and it should only trigger when the child is hovered. Here's an example on Tailwind Play https://play.tailwindcss.com/W4C3J3tW6E

<main id="parent" class="h-screen flex justify-center items-center
hover:bg-blue-100 pointer-events-none">
  <div id="child" class="bg-red-200 w-96 h-72 flex pointer-events-auto">
  </div>
</main>

Upvotes: 24

Related Questions