Published on

TailwindCSS - Change Label When Radio Button Checked

Authors
  • Name
    Ripal & Zalak
    Twitter

TailwindCSS - Change Label When Radio Button is Checked

In TailwindCSS, you can modify the label when a radio button is selected using the peer class (introduced in Tailwind v2.2) and the :has() pseudo-class (introduced in Tailwind v3.4). Here’s how you can do it.

Using peer to Change Label When Radio Button is Checked

<div>
  <label>
    <input type="radio" name="option" id="option1" class="peer hidden" />
    <div class="rounded p-2 peer-checked:bg-blue-500 peer-checked:text-white">Option 1</div>
  </label>
  <label>
    <input type="radio" name="option" id="option2" class="peer hidden" />
    <div class="rounded p-2 peer-checked:bg-blue-500 peer-checked:text-white">Option 2</div>
  </label>
</div>

Explanation:

  • peer is applied to the input, making it the reference element.
  • peer-checked:bg-blue-500 changes the background color when the input is checked.
  • peer-checked:text-white changes the text color when selected.

Using has() Pseudo-Class (Tailwind v3.4+)

<div class="flex gap-2">
  <label class="rounded bg-gray-200 p-3 has-[:checked]:bg-green-500 has-[:checked]:text-white">
    <input type="radio" name="option" class="hidden" />
    <div>Option 1</div>
  </label>
  <label class="rounded bg-gray-200 p-3 has-[:checked]:bg-green-500 has-[:checked]:text-white">
    <input type="radio" name="option" class="hidden" />
    <div>Option 2</div>
  </label>
</div>

Explanation:

  • The has-[:checked] class applies styles to the label when the input inside is checked.
  • Background and text color change dynamically when selected.

FAQs

1. Can I use TailwindCSS to change the label’s text when checked?

No, TailwindCSS does not provide a direct way to change the label’s text dynamically. You would need JavaScript for that.

2. What is the difference between peer and has() in TailwindCSS?

  • peer allows you to style sibling elements based on the state of an input.
  • has() lets you style parent elements when they contain a checked input (Tailwind v3.4+).

3. How do I make a custom radio button with TailwindCSS?

You can use peer, checked, and before pseudo-elements to create fully custom radio buttons.