sidp.dev

Removing :focus outline without destroying accessibility

Working with forms and buttons, there’s a thing that often comes up when implementing the different states; the blue border focus border. It’s there to let users know where the focus on the page is, and it’s necessary for keyboard navigation.

For some designs though, it might not be desirable. Maybe you’re into more subtle effects, maybe you’re working with a designer who is. Well, being a crafty person who is in complete control of what computers do, you can simply decide to hide it.

/* Don’t do it */
:focus {
	outline: 0;
}

This solves the cosmetic issue, but while doing so it also completely destroys keyboard navigation. The user can’t see where focus is, which is comparable to hiding the cursor for users who use a mouse.

The simple solution to the problem is: just don’t do it. Leave the outline and accept it. With time you might even learn it like it.

If you do remove it, I suggest that you should also add it back when the user tabs. Here’s the solution to that. (TODO)

window.addEventListener('keydown', ev => {
	if (ev.key === 'Tab') {
		document.documentElement.classList.add('tabbed');
	}
});

window.addEventListener('mousedown', () => {
	document.documentElement.classList.remove('tabbed');
});

This allows you to remove the outline, but add it back when the user presses the tab key on the page, indicating that they want to use keyboard navigation.

:focus {
	outline: 0;
}

.tabbed :focus {
	outline: 2px solid #000;
}

You can try it out on this CodePen.

An added bonus is that you can now make the focus state super obvious. Make it red and big and don’t let anyone miss it.