Custom accessible checkbox and radio elements
by jamessouth
HTML
<h1>
Custom Accessible Form Inputs
</h1>
<p>
These custom elements are rendered using CSS only with no images. Best efforts have been made to make them acessible but I haven't tested with a screenreader (yet).
</p>
<p>
The inputs are hidden using established techniques to still allow focus and are replaced using pseudo elements to allow styling.
</p>
<p>
Tested on IE11 (IE9, IE10 Emulation Only), Edge, Chrome, Firefox, and Opera.
</p>
<form>
<input type="radio" name="radio" id="radio1" />
<label for="radio1">Radio One</label>
<input type="radio" name="radio" id="radio2" />
<label for="radio2">Radio Two</label>
<hr/>
<input type="checkbox" name="checkbox" id="checkbox1" />
<label for="checkbox1">Checkbox One</label>
<input type="checkbox" name="checkbox" id="checkbox2" />
<label for="checkbox2">Checkbox Two</label>
<hr/>
<input type="radio" name="radio3" id="radio3" disabled />
<label for="radio3">Disabled Radio </label>
<input type="checkbox" name="checkbox3" id="checkbox3" disabled />
<label for="checkbox3">Disabled Checkbox </label>
</form>
CSS
*,
*:before,
*:after {
box-sizing: border-box;
}
label[for] {
display: block;
margin-bottom: 1rem;
cursor: pointer;
}
input[type=radio],
input[type=checkbox] {
/* Hidden yet focusable.*/
border: 0;
clip: rect(0 0 0 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1px;
}
input[type=radio] + label,
input[type=checkbox] + label {
position: relative;
padding-left: 1.5rem;
}
input[type=radio] + label:before,
input[type=checkbox] + label:before {
position: absolute;
top: 0;
left: 0;
width: 1rem;
height: 1rem;
display: block;
border: 2px solid black;
text-align: center;
line-height: 0.5;
font-size: 1.2rem;
content: "";
}
input[type=radio] + label:before {
border-radius: 100%;
background-color: white;
}
/* Checked */
input[type=radio]:checked + label:before {
background-color: black;
border: 2px solid white;
box-shadow: 0 0 0 2px black;
width: calc(1rem - 4px);
height: calc(1rem - 4px);
top: 2px;
left: 2px;
}
input[type=checkbox]:checked + label:before {
content: "";
background-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA0NDguOCA0NDguOCI+PHBhdGggZD0iTTE0Mi44IDMyMy44NUwzNS43IDIxNi43NSAwIDI1Mi40NWwxNDIuOCAxNDIuOCAzMDYtMzA2LTM1LjctMzUuNyIvPjwvc3ZnPg==);
background-size: cover;
}
/* Focus */
input[type=radio]:focus + label:before,
input[type=checkbox]:focus + label:before {
border-color: #3b99fc;
}
/* Focus */
input[type=radio]:disabled + label,
input[type=checkbox]:disabled + label {
cursor: text;
}
input[type=radio]:disabled + label:before,
input[type=checkbox]:disabled + label:before {
border-color: silver;
color: silver;
}