7

I've used some CSS to make mobile-friendly 'radio' buttons by hiding the inputs and using the label elements instead. The code is below, but I've made a jsFiddle for convenience.

My problem is that a major usability issue arises when using a keyboard to navigate the form: the fields are no longer tabbable. I've tried adding tabindex attributes to the hidden inputs, the labels and to the div. The first two do not work at all, adding tabindex to the div works (the div is highlighted), but I can't interact with the form elements at all (with the arrow keys for example).

Is it possible to fix this just with CSS/HTML? I'd rather not fall back to javascript, but if there's no other way I guess I'll have to.

<input type='text'>
<div class='radio-select'>
  <input checked="checked" id="no" name="yes_no" value="False" type="radio">
  <label for="no">
    No
  </label>
  <input id="yes" name="yes_no" value="True" type="radio">
  <label for="yes" >
    Yes
  </label>
</div>
<input type='text'>
<style>
.radio-select label{
    background: #f00;
    border:1px solid #ddd;
    border-radius:10px;
    padding:10px;
    margin:5px 0;
    max-width:200px;
    clear:both;
    display: block;
    cursor:pointer;
}
.radio-select input[type='radio']{
    display: none;
}
.radio-select input[type='radio']:checked + label{
    background:#0f0 !important;
}
.radio-select input[type='radio']:checked + label:before{
    content:"✔";
}
</style>

1 Answer 1

10

If you hide the inputs by setting their opacity to 0 they will still be tabbable:

.radio-select input[type='radio']{
    opacity:0;
    filter:alpha(opacity=0);
    position:absolute
}

jsfiddle

4
  • This focuses them, yes, but doesn't actually select them. I could add some javascript to do that, but it's not really ideal.
    – fredley
    Commented Apr 17, 2014 at 10:17
  • You shouldn't set your radio button's display to none, you should set their opacity to 0 so they are not visible but tabbable and selectable through the keyboard.
    – W.D.
    Commented Apr 17, 2014 at 10:20
  • @TomMedley, I've updated the code. Now you can tab through the label tags with arrow keys.
    – W.D.
    Commented Apr 17, 2014 at 10:46
  • In my page (minimal: just some <input type="radio" /> in <label> without any tabindex="0" attributes on any elements and no CSS/styles at all) and I see that the radio inputs cannot be focused with the Tab key at all. Are you sure this works?
    – Dai
    Commented May 20, 2020 at 3:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.