SmartCodingTips

Group Hover & Focus Within in Tailwind CSS

Tailwind CSS provides group and group-hover utilities that allow you to style child elements based on the hover or focus state of a parent container. Similarly, focus-within allows styling when any child element has focus.

1. Using Group Hover

Add group to a parent and use group-hover: on children:

Hover over this box to change my text color.


<div class="group p-4 border rounded hover:bg-gray-100">
    <p class="group-hover:text-blue-600 dark:text-blue-400">
        Hover over this box to change my text color.
    </p>
</div>
            

2. Using Focus Within

Style a parent when any of its children receive focus:


<div class="border-2 p-4 rounded focus-within:border-blue-500">
    <label class="block text-sm mb-1">Your Email:</label>
    <input type="email" class="w-full px-3 py-2 border rounded">
</div>
            

3. Common Use Cases

  • Dropdown menus triggered on hover
  • Card components highlighting details on hover
  • Input validation highlighting containers on focus

4. Best Practices

  • Ensure group is on the parent container
  • Use transitions for smoother UI
  • focus-within improves accessibility for keyboard navigation

Conclusion

Group hover and focus-within are powerful tools to build complex interactions without JavaScript. They help you create accessible, intuitive UIs with minimal effort using just utility classes.