Radio Pills with Tailwind

Here is a quick tip on building “radio pills” with TailwindCSS, inspired by Scott O’Hara’s brilliant work. The goal here is to make an accessible form element that also has visual polish and purpose.1


This won’t be like a recipe on some blog, where I drone on and on for paragraphs about my childhood. Here’s the CodePen, enjoy:

See the Pen Tailwind CSS - Radio Pills by Stephen Margheim (@smargh) on CodePen.

And, if you want to apply this to a Rails form, here’s the basic idea:

<fieldset class="inline-block whitespace-nowrap p-px border-2 rounded-full focus-within:outline focus-within:outline-blue-400">
<%= form.collection_radio_buttons(:attribute, ["Option 1", "Option 2"], :itself, :itself) do |builder| %>
<span class="relative inline-block">
<%= builder.radio_button class: "sr-only peer" %>
<%= builder.label(class: "border-2 border-transparent rounded-full block py-1 px-2 peer-checked:bg-blue-500 peer-checked:text-white hover:bg-blue-200 hover:border-blue-500") %>
</span>
<% end %>
</fieldset>

  1. If you want to explore more styled form controls that are still well-structured and accessible, Scott has a wonderful collection that is well worth your time.