We're all guilty of doing outline:none
, without giving it much thought, for getting rid of those ugly blue outlines of our form control elements such as buttons and input fields. But if we are considering to make our website more accessible which we DEFINITELY should, the first suggestion we'll read in any of the accessibility checklist is to NEVER do outline:none
because then it becomes nearly impossible for keyboard users to navigate through our website.
So how do we overcome this problem?
Simple. Give some proper styles to the outline
such as outline: 2px solid your_choice_of_colour
and you won't get the default outline styles anymore!
But if we are willing to take an extra step to first identify (or at least try to) the keyboard user and only show those outlines (styled or un-styled) to them and the rest can go on about their lives without ever knowing them outlines!
Here's how we can do that -
First identify if the user has hit the tab
key and if they did add a class to your body
.
function handleTab(e) {
if (e.keyCode === 9) { // "hey I am a keyboard user"
document.body.classList.add('user-tabbing');
window.removeEventListener('keydown', handleTab);
}
}
window.addEventListener('keydown', handleTab);
Second, add your specific styles and voila!
body button:focus,
body input:focus,
body select:focus,
body textarea:focus {
outline: 2px solid yellow;
}
body:not(.user-tabbing) button:focus,
body:not(.user-tabbing) input:focus,
body:not(.user-tabbing) select:focus,
body:not(.user-tabbing) textarea:focus {
outline: none
}
What are some of your tips for making the web more accessible for all?