DEV3 Technologies home

DEV3 Developer Forum

How do I style a child on parent hover or a sibling when an input is checked in Tailwind (group and peer)?

dev3 ·

I need an icon to change color when the parent card is hovered, and a label to change when a hidden checkbox next to it is checked. Doing it with JavaScript state feels heavy. How do group and peer work?

#tailwind#group#peer#variants

0

1 reply

dev3 · Accepted answer

group: react to a parent's state

Add group to the parent, then use group-* variants on any descendant.

<a href="/docs" class="group flex items-center gap-3 rounded-lg p-4 hover:bg-slate-50">
  <svg class="size-5 text-slate-400 transition-colors group-hover:text-blue-600">...</svg>
  <span class="font-medium group-hover:underline">Documentation</span>
  <span class="ml-auto translate-x-0 opacity-0 transition group-hover:translate-x-1 group-hover:opacity-100">&rarr;</span>
</a>

Other group states: group-focus-visible, group-has-[:checked], group-data-[open=true], group-aria-expanded.

Name groups to avoid nesting conflicts: group/card on the parent and group-hover/card: on the child.

peer: react to a previous sibling's state

The peer must come before the styled element in the DOM (CSS sibling selectors only look forward).

<label class="block">
  <input type="checkbox" class="peer sr-only">
  <span class="inline-flex rounded-full border px-4 py-2
               peer-checked:border-blue-600 peer-checked:bg-blue-50 peer-checked:text-blue-700
               peer-focus-visible:ring-2 peer-focus-visible:ring-blue-600">
    Express shipping
  </span>
</label>

Use sr-only (not hidden) so the input stays focusable and accessible to keyboards and screen readers.

Floating label pattern:

<div class="relative">
  <input id="email" placeholder=" " class="peer w-full rounded border px-3 pt-5 pb-1">
  <label for="email" class="absolute left-3 top-3.5 text-slate-500 transition-all
         peer-focus:top-1 peer-focus:text-xs peer-[:not(:placeholder-shown)]:top-1 peer-[:not(:placeholder-shown)]:text-xs">
    Email
  </label>
</div>

Pitfalls

  • Peer styling fails if the element is placed before the peer or wrapped in another element between them (it must be a sibling, peer-has can help in some layouts).
  • group-hover on touch devices only applies on hover-capable devices in Tailwind 4.
  • For more complex state (open menus), prefer data-* attributes with data-[state=open]: variants.

Accessible interactive example: FAQ accordion with details/summary.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.