Experiments

Advanced Tailwind: Multiple hover interactions

Jul 1st, 2024

3 minutes mins to read

Share article


<div 
    class="bg-white has-[.blue:hover]:bg-blue-500 has-[#red:hover]:bg-red-500 has-[[data-color='green']:hover]:bg-green-500"
>
    <button class="blue">Blue</button>
    <button id="red">Red</button>
    <button data-color="green">Green</button>
</div>

Utilizing the has Utility in Tailwind

The has utility in Tailwind is a powerful tool that allows you to apply styles to a parent element based on the state of its child elements.

How the has Utility Works

The has utility targets the parent element and changes its style when a specified condition is met in any of its child elements. This is particularly useful for creating effects where the state of a child element (like hovering focusing, or being active) influences the parent element.

Combining has with Class and State Selectors

In our code example, we use the has utility to change the background color of a parent div based on the hover state of specific child buttons:

In this example:

<div class="has-[.red:hover]:bg-red-500">
    <button class="red">
</div>

Changes the parent div's backgrounnd based on the state of a child, selected by class. But, the selector for the child can be as specific as needed.

Example:

<div 
    class="has-[button[data-color='green']:hover]:bg-green-500"
>
    <button data-color="green">Green</button>
</div>

In this case the background changed sames as before, but targeting the state of a button with data attribute data-color="green".

© 2025, AdrianRdz - All rights reserved.