DEV Community

Cover image for Create custom keyboard accessible radio buttons

Create custom keyboard accessible radio buttons

Lindsey Kopacz on August 05, 2019

Originally posted on a11ywithlindsey.com. Hey friends! Today we'll be creating custom keyboard accessible radio buttons! This blog post is a follo...
Collapse
 
link2twenty profile image
Andrew Bone

Is there a reason you went for wrapping each input-label combo in a div rather than using the label element?

<div class="radio-wrapper">
  <input type="radio" name="animal" id="elephant" />
  <label for="elephant">Elephant</label>
</div>

Rather than

<label class="radio-wrapper">
  <input type="radio" name="animal" />
  Elephant
</label>

Or is it a simple case of either will do but you went with the div? 🙂

Collapse
 
elizabethschafer profile image
Elizabeth Schafer

One reason to do it this way is that explicit labels (input+label combo) have better support with assistive tech. Implicit labels (label wrapping an input) don't work with Dragon Naturally Speaking.

a11ysupport.io/tech/html/label_ele...

Collapse
 
lkopacz profile image
Lindsey Kopacz

I would take a look at the responses to this. I prefer explicit association but others put their reasons in.

Collapse
 
lkopacz profile image
Lindsey Kopacz

Because I wanted to.

Collapse
 
link2twenty profile image
Andrew Bone

Cool, thanks 🙂

Was just checking there wasn't some reason I wasn't aware of 🙂

Thread Thread
 
lkopacz profile image
Lindsey Kopacz

haha It's how I prefer to write my inputs.

Collapse
 
elizabethschafer profile image
Elizabeth Schafer

I love the suggestions to keep the native radio buttons visible while you're working on a custom replacement and to use the :checked pseudo-class to style selected radio buttons. It's really easy to make custom radio buttons that are accidentally out of sync with the native controls.

Collapse
 
thekashey profile image
Anton Korzunov

Quite similar to mine HTML State.

And there is one moment I would like to change in your example - please don't use position:absolute to position "radio" visuals - it's not scalable.

Let's try to do the same, but with position:static

Collapse
 
mikewheaton profile image
Mike Wheaton

Thanks for this! I'm curious about opacity: 0 instead of display: none for the original radio button. Is this because screen readers are still using the original/hidden radio button?

Collapse
 
lkopacz profile image
Lindsey Kopacz

That's correct! I would check out @scottohara 's post about why: scottohara.me/blog/2017/04/14/incl...

Collapse
 
eli profile image
Eli Bierman

Using this for some radio buttons right now, thank you for the helpful guide!