Tip #8: Use focus-visible to improve keyboard accessibility

  • — Frontend

  • 1 min. read

  • — 2/15/2023

Accessibility (aka a11y) is a core web vital used by the Lighthouse audit to rank websites accordingly, so its important that the websites we build adhere to the standards expected thereof.

One metric of accessibility is keyboard navigability and friendliness. Typically this just means that all links can be "tabbed" to by someone using a keyboard and that they're easily recognized as being "active" when the tab selection is on a particular link.

To achieve this, I used to manually define a focus: state for every link on my website, which lead to a bit of DRY.

Nowadays, I don't use focus: ever thanks to a better utility: focus-visible:.

You see, focus-visible: is a very particular pseudo that only gets triggered when a keyboard tab is being used (compare this to focus: which will get applied on both tab and mouse click).

Instead of defining a particular focus effect for every link, I instead add focus-visible: styles inside of my CSS file and globally select any interactable elements:

@tailwind base;
@tailwind components;
@tailiwnd utilities;

input {
	@apply focus:outline-none focus-visible:ring-4 focus-visible:ring-blue-500 transition duration-300 ease-in-out

Notice two things here:

  1. I'm still defining a focus:outline-none, this will remove any annoying focus events the browser automatically applies when the user clicks on something with their mouse
  2. I'm compensating for a focus state by using focus-visible: on keyboard tabbing and using a focus ring for a better effect (I wrote a bit about focus rings if you want to read more about them)

By default, every interactable element (defined in the above CSS stylesheet) will have a default, tab-focused state. You no longer need to define one using focus:!

Shaun Chander

hey (again), I'm shaun

I'm posting 3 tips on creative web development daily. Subscribe below to to get tips delivered straight into your inbox!