Display focus-indicator for styled radio and checkbox
When styling radio buttons
and checkboxes
by hiding them visually
and using pseudo-elements,
along with pseudo-classes,
please ensure to add custom focus indicator.
Otherwise, a user accessing the user interface via keyboard, has no idea, what is the active element/field.
CodePen example - Styled radio & checkbox without focus-indicator
Try accessing the below example using keyboard; tab
, space
, enter
, up/down/left/right
arrow keys.
See the Pen Styled radio & checkbox w/o focus-indicator by Sarbbottam Bandyopadhyay (@sarbbottam) on CodePen.
Was that difficult?
Solution
With respect to the above example, add a custom focus indicator to the pseudo-element
, when the field is focused.
[type="checkbox"]:focus + label:before,
[type="radio"]:focus + label:before{
/*
add a style that visually distinguishes it from others
border: -
box-shadow: -
...
better to have a consistent treatment across the page.
*/
outline: 2px solid #50e3c2;
}
Irrespective of the approach, please ensure any active element is visually distinguishable from others.
CodePen example - Styled radio & checkbox with focus-indicator
Try accessing the example using keyboard; tab
, space
, enter
, up/down/left/right
arrow keys.
See the Pen Styled radio & checkbox w/ focus-indicator by Sarbbottam Bandyopadhyay (@sarbbottam) on CodePen.
It’s much better than the previous example.
If using, native HTML elements as is, you get it (focus outline) for free.
CodePen example - Unstyled radio & checkbox (default focus-indicator)
See the Pen Unstyled radio & checkbox (default focus-indicator) by Sarbbottam Bandyopadhyay (@sarbbottam) on CodePen.
Protip
Never use display: none
; any element or its ancestor with display
set to none
, will not be reachable via keyboard.
It is out of the tab order
.
If you have enjoyed reading this post you can follow me on twitter @sarbbottam and learn about any new posts. Opinions expressed are solely my own and do not express the views or opinions of my employer.