The :focus-visible Trick

Avatar of Chris Coyier
Chris Coyier on

DigitalOcean provides cloud products for every stage of your journey. Get started with $200 in free credit!

Always worth repeating: all interactive elements should have a focus style. That way, a keyboard user can tell when they have moved focus to that element.

But if you use :focus alone for this, it has a side effect that a lot of people don’t like. It means that when you click (with a mouse) on an interactive element, you’ll see the focus style. Arguably, you don’t need that feedback as a mouse user, because you just moved your cursor there and clicked. Whatever you think of that, it’s annoyed so many people over the years that they remove focus styles entirely, which is a gnarly net loss for accessibility on the web.

What if we could apply focus styles only when the keyboard is used to focus something, not the mouse? Lea Verou put a finger on this a few years back:

That was in response to Chrome dropping the feature behind a flag. Clever clever.

Fast forward a couple of years, Chrome is releasing it without a flag. They are on board with Lea’s idea:

By combining :focus-visible with :focus you can take things a step further and provide different focus styles depending on the user’s input device. This can be helpful if you want the focus indicator to depend on the precision of the input device:

/* Focusing the button with a keyboard will show a dashed black line. */
button:focus-visible {
  outline: 4px dashed black;
}
  
/* Focusing the button with a mouse, touch, or stylus will show a subtle drop shadow. */
button:focus:not(:focus-visible) {
  outline: none;
  box-shadow: 1px 1px 5px rgba(1, 1, 0, .7);
}

I might suggest trying those selectors without the button, making them globally applied!

There is more to dig into, so I’ll link up some more stuff here:

  • The Chromium Blog post covers the heuristics of the selector. It’s tricky. It’s like there is an algorithm to determine if :focus-visible is going to match or not, which you just largely need to trust. It also covers the idea that Firefox has long had :-moz-focusring, but the behavior is different enough that they don’t recommend using it if you’re shooting for consistent behavior.
  • Matthias Ott blogged about it with some good info, like using the official polyfill and how to look at the styles properly in DevTools (there is a new checkbox for it).
  • We’ve covered this before. In that, we noted Lea’s tweet that she thought usage would explode when it ships for real. Let’s see (and hope)!
  • Our almanac entry has a bunch of details.