Coding Accessible Checkbox Inputs

How I build accessible checkboxes

This blog post was written by and published 12th July 2016.

How I (used to) code styled checkboxes and radio buttons

Skip to accessible method

Before I understood the importance of accessibility I coded stylised radio buttons using a hidden input and a few span tags, using the inner span to style the button and a bit of jQuery to update the hidden input on clicking.

The issue with this way of doing radio buttons is its totally in-accessible, meaning if you don’t use a mouse you cant select the options.

Heres how not to build accessible buttons: (accessible version is below)

See the Pen CCS & jQuery Check Box & Radio Input Custom Styling by Nick McBurney (@NickMcBurney) on CodePen.

How I code stylised accessible checkboxes and radio buttons

Using just some basic HTML tags and CSS3 pseudo-class selectors we can create keyboard friendly (accessible) checkbox and radio inputs which can be styled beyond their default styles.
View demo

HTML Structure

To create accessible stylised inputs I used some basic HTML tags:
<fieldset> to hold it all together, <legend> to describe the purpose of the buttons, <input /> to hold the checked or toggled state, and <label> to style our custom button.

Heres the full HTML structure

<fieldset class="question">
	<legend>Accessible Radio Buttons:</legend>
	<input type="radio" name="radio" id="yes"><label for="yes">Yes</label> 
	<input type="radio" name="radio" id="no"><label for="no">No</label>

The fieldset tag is used to group related elements in a form or in this case, group related options of the question together. The legend tag defines the question or caption for the fieldset element and this is what is read out by screen readers.

Its important to link the label to the input using the input’s ‘id’ property and the label’s ‘for’ property to tell the browser that these elements are connected. Once you add this code you can use the label element to toggle the input’s check/unchecked value.

Simple example:

<input type="checkbox" id="checkbox"><label for="checkbox">Click me</label>


CSS Stylings

Now we can control the input using the label element we can add styles to make the label look like a button, and add additional styles for when the input is focused and checked. Thanks to CSS3 we can use the :focused and :checked pseudo-class selectors along with the + adjacent selector (which selects only the element which is immediately preceded by the former element) to tell other DOM elements that the input is being focused and checked.

input:focus + label {
	// input is focused highlight sibling label
	box-shadow: 0px 0px 6px 0px rgba(0,142,219,1);
	outline: 0 none;

input:checked + label {
	// input is checked style sibling label
	background: #62c8d0;
	color: #fff;

Have look at the full code used below

See the Pen Accessible Radio Buttons & Input Fields by Nick McBurney (@NickMcBurney) on CodePen.

Accessible input compatibility