Tailwind & Alpine.js radio button styling
I recommend to use a common size
variable and bind it to the radio input element via x-model
. Currently you have as many independent isChecked
states as many button you have, which is - I guess - not the expected behavior.
The modified example:
<fieldset x-data="{size: null}">
<legend>Choose size</legend>
<div class="mt-4 grid grid-cols-3 gap-3 sm:grid-cols-4">
<label for="small"
class="border rounded-md py-3 px-3 flex items-center justify-center text-sm font-medium uppercase sm:flex-1 cursor-pointer focus:outline-none checked:bg-indigo-600 checked:border-transparent checked:text-white checked:hover:bg-indigo-700"
:aria-checked="size == 's'"
:class="size == 's' ? 'bg-indigo-600 border-transparent text-white hover:bg-indigo-700' : 'bg-white border-gray-200 text-gray-900 hover:bg-gray-50'">
<input x-model="size" id="small" type="radio" name="size-choice" value="s" class="sr-only" aria-labelledby="size-choice-0-label">
<p id="size-choice-0-label">
Small
</p>
</label>
<label for="medium"
class="border rounded-md py-3 px-3 flex items-center justify-center text-sm font-medium uppercase sm:flex-1 cursor-pointer focus:outline-none checked:bg-indigo-600 checked:border-transparent checked:text-white checked:hover:bg-indigo-700"
:aria-checked="size == 'm'"
:class="size == 'm' ? 'bg-indigo-600 border-transparent text-white hover:bg-indigo-700' : 'bg-white border-gray-200 text-gray-900 hover:bg-gray-50'">
<input x-model="size" id="medium" type="radio" name="size-choice" value="m" class="sr-only"
aria-labelledby="size-choice-0-label">
<p id="size-choice-0-label">
Medium
</p>
</label>
</div>
</fieldset>
I have just replaced every selection-checking with the suggested method. Furthermore putting a @click
event to the label caused some weird double-clicking behavior for me. Adding a @click.prevent
modifier solved this issue, but after that the radio element does not received the click event. My suggestion avoided this issue because the radio input element itself became the source of the information.