- Instant help with your CSS coding problems

Add class to child when hovering on parent in TailwindCSS

Question:
How to add class to child when hovering on parent in TailwindCSS?
Answer:
<a href="#" class="group rounded-lg w-80 p-6 flex flex-col border border-gray-300 bg-white hover:bg-sky-500">
    <h3 class="group-hover:text-white font-semibold">Task</h3>
    <p class="group-hover:text-white text-slate-500 text-sm">Lorem ipsum dolor sit amet consectetur adipisicing elit. Illum, alias.</p>
</a>
Description:

If you want to change the styling of an element depending on the status of the parent element, you can easily do so using standard CSS as follows:

<a href="#" class="item">
    <h3>Task</h3>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Accusamus, nemo.</p>
</a>

and the corresponding vanilla css:

.item {
  border:1px solid #ccc;
  padding: 24px;
  border-radius: 8px;
  max-width: 320px;
  display: flex;
  flex-direction: column;
  
}

.item h3 {
  font-weight: bold;
}

.item p {
  font-size:14px;
  color: #888;
}

.item:hover {
  background-color: #0ea5e9;
}

.item:hover h3,
.item:hover p {
  color:white;
}

And the result is in case of mouse out and mouse over:

Basic vanilla CSS mouse outBasic vanilla CSS mouse over

To get the same result using TailwindCSS, you can use the group helper class and the group-* modifiers. The group class must be placed on the parent element and the group-* modifiers can be used for the required child elements.

To achieve the final result shown above, the following TailwindCSS code is required:

<a href="#" class="group rounded-lg w-80 p-6 flex flex-col border border-gray-300 bg-white hover:bg-sky-500">
    <h3 class="group-hover:text-white font-semibold">Task</h3>
    <p class="group-hover:text-white text-slate-500 text-sm">Lorem ipsum dolor sit amet consectetur adipisicing elit. Illum, alias.</p>
</a>

 

 

Share "How to add class to child when hovering on parent in TailwindCSS?"
Interesting things
OpanAi's ChatGPT