點燈坊

失くすものさえない今が強くなるチャンスよ

Using group-hover to Style the Child Element

Sam Xiao's Avatar 2022-01-25

hover modifier styles the element when hovered, whereas group-hover modifier style the child element when hovered.

Version

TailwindCSS 3.0

group-hover

hover000

The child is red when the parent element is hovered.

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.tailwindcss.com"></script>
  <title>TailwindCSS</title>
</head>
<body>
  <div class="group">
    <div class="w-20 h-20 mx-auto bg-gray-300 group-hover:bg-red-500"></div>
  </div>
</body>

Line 10

<div class="group">
  <div class="w-20 h-20 mx-auto bg-gray-300 group-hover:bg-red-500"></div>
</div>
  • group : set the parent element when hovered
  • w-20 : set the child element’s width
  • h-20 : set the child element’s height
  • mx-auto : make the child element horizontal center
  • bg-gray-300 : set the child element’s background color
  • group-hover:bg-red-500 : style the child element when the parent element is hovered

Conclusion

  • By applying group modifier on the parent element, we can style the child element by group-hover modifier when the parent element is hovered

Reference

TailwindCSS, Styling based on parent state