Working on a form that has some custom radio button styling and wanted to check the way I normally do this.
To avoid Javascript, I typically have a radio input wrapped inside a label and a div following the input. I then style the div depending on the checked state.
This is some example markup:
label input:checked ~ span {
background: red;
}
<label for="10000">
<input type="radio" id="10000" name="coveramount" value="10000">
<span>£10,000</span>
</label>
(there's normally classes on the elements)
Is the span inside a label correct? Is there a better way of doing this with another tag or similar for accessibility?
The HTML in your question is fine. This is a very simple and reliable way of styling radio and checkbox elements.
There are some potential accessibility issues to watch out for, more to do with the CSS than the HTML.
Will the <input>
element itself be visible, in your design? It's common to hide the actual radio/checkbox input, and use CSS background images to provide fancy-looking versions of the checked and unchecked states. If you do this, remember to:
label input:focus ~ span
display:none
, visibility:hidden
, or the HTML hidden
attribute to hide the real radio/checkbox. These will all prevent the input from being operable by keyboard-only users, and screen reader users (pointer users can click on the <label>
element). That's because they all cause the input to be removed from the keyboard tabbing order, and removed from the accessibility tree which is sent to assistive tech. If you need to hide the real input element, use an approach like Bootstrap's .sr-only
class or HTML5Boilerplate's .visuallyhidden
class. For more detail about this, see:
Another potential issue is with use of colour. Don't rely on a change of colour alone to indicate a checked control, that's a WCAG failure. Native radios and checkboxes involve a shape change (i.e. the bullet which fills the circle). Be aware that CSS colours get overridden when a Windows High Contrast theme is in use. If background: red
is the only clue to a checked (or focused) radio option, Windows High-Contrast users won't know what's going on.