With Chromium 86 and now recently Firefox 85 supporting :focus-visible
, it’s a good time to refer to this post by Matthias Ott:
The
:focus-visible
pseudo-class lets you show focus styles only when they are needed, using the same heuristic that the browser uses to decide whether to show the default focus indicator.
You use :focus-visible
just like you use :focus
. To properly hide focus rings on “mouse focus” though, you’ll need to add an extra rule-set in which you combine :focus
with (a negated) :focus-visible
:
/* Show focus styles on keyboard focus. */
:focus-visible {
outline: 3px solid blue;
}
/* Hide focus styles if they're not needed, for example,
when an element receives focus via the mouse. */
:focus:not(:focus-visible) {
outline: 0;
}
💁♂️ This extra rule-set is needed because browser vendors add a default outline using :focus
through their User Agent StyleSheet.
In the (near?) future this extra rule-set will no longer be needed as the HTML spec now prescribes that UA StyleSheets use :focus-visible
to add the default outline.
Awaiting the work Igalia is doing on this, Safari does not yet support :focus-visible
, but in the meantime you can use a polyfill.