Published on

How to Make Parent Div Trigger Hover Styles on Child Elements in Tailwind CSS

Authors
  • Name
    Ripal & Zalak
    Twitter

How to Make Parent Div Trigger Hover Styles on Child Elements in Tailwind CSS

By default, hover effects in Tailwind CSS apply only to the specific element being hovered. However, with group-hover, you can make the parent element trigger hover effects on its children.

Solution: Use group and group-hover

Tailwind provides a utility class called group, which allows child elements to respond when the parent is hovered.

Example Code:

<a href="/dashboard" class="group block w-72 pb-3 text-lg text-gray-200">
  <div class="flex flex-row space-x-8">
    <div class="h-8 w-8 -translate-x-7 transform rounded group-hover:bg-green-300"></div>
    <div class="flex -translate-x-10 -translate-y-1 transform flex-row items-center space-x-8">
      <i class="bi bi-columns-gap translate-x-1 transform group-hover:text-green-300"></i>
      <h2
        class="translate-y-1 transform text-base group-hover:font-semibold group-hover:text-green-300"
      >
        Dashboard
      </h2>
    </div>
  </div>
</a>

How It Works:

  • The parent <a> element has the group class.
  • Inside it, child elements use group-hover: to apply styles when the parent is hovered.
  • The background color, text color, and font weight change when the parent is hovered.

Alternative: Use [&>*]:hover for Global Child Hover Effects

If you want all direct child elements of a parent to change on hover, use this approach:

<div class="p-4 hover:bg-gray-800 [&>*]:hover:text-green-300">
  <p>Item 1</p>
  <p>Item 2</p>
</div>

This applies text-green-300 to all child elements when hovering over the parent.

FAQs

1. Why isn’t group-hover working?

Ensure that:

  • The parent element has the group class.
  • The child elements have group-hover: styles.
  • No conflicting styles are overriding group-hover.

2. Can group-hover work with focus and active states?

Yes! Use group-focus or group-active:

<button class="group border border-gray-400 p-4">
  <span class="group-hover:text-red-500 group-focus:text-blue-500">Hover or Focus Me</span>
</button>