Simple images as radio buttons with tailwindcss 2.2.x

11:07 PM July 18 2021 frontend

Example: https://play.tailwindcss.com/W6mCYXqAOX

Tailwind CSS v2.2 introduced the peer utility class that allows us to target sibling elements and style them based on the 'peer' element state.

This feature is only available in Just-in-Time mode, so please remember to add mode: 'jit' in your tailwind.config.js file

With this utility we can change a label style based on the radio button input 'checked' state, as long they are direct siblings in the HTML.

We need to add the 'peer' class to the element that will change its state, and then the peer and the desired pseudo-class selector for that state, in this case we will use peer-checked

<form>
  <label for="option_1">
    <input type="radio" id="option_1" class="peer">
    <span class="peer-checked:border-green peer-checked:border-4">...</span>
  </label>

  <label for="option_2">
    <input type="radio" id="option_2" class="peer">
    <span class="peer-checked:border-green peer-checked:border-4">...</span>
  </label>
</form>

In this example, the label will get a green border when the radio button is selected. You can do the same with checkboxes or other elements, and with almost all pseudo-classes available.

Now the only step missing to create a radio button disguised as an image, its to add the utility class 'hidden' to the input element, and add an image in the span element in the example, or just add the tag as a sibling to the input element and add the classes to that element.

<div class="flex space-x-4">
  <label for="opt1" >
    <input type="radio" id="opt1" name="test" class="peer hidden" />
    <img src="https://dummyimage.com/200x200/000/fff" alt="" class="peer-checked:border-green-500 peer-checked:border-4" />
  </label>

  <label for="opt2" >
    <input type="radio" id="opt2" name="test" class="peer hidden" /> 
    <img src="https://dummyimage.com/200x200/000/fff" alt="" class="peer-checked:border-green-500 peer-checked:border-4" />
  </label>
</div>

https://play.tailwindcss.com/W6mCYXqAOX