CSS pseudo-classPseudo-classes

:focus-visible

Matches a focused element only when the browser decides the indicator should be visible, such as during keyboard navigation.

On this page

Example

#
CSS
.btn:focus-visible {
  outline: 3px solid #f59e0b;
  outline-offset: 3px;
}
Preview

Definition and usage

#

The :focus-visible pseudo-class is a smarter version of :focus. The browser judges for itself whether the user would benefit from a visible indicator. While tabbing with the keyboard it always matches, while after clicking a button with the mouse it usually doesn’t, since in that case it’s already clear where the focus is.

Text fields are an exception: after a mouse click they match both :focus and :focus-visible, because the user is about to type on the keyboard and needs to see which field is active.

Thanks to this, you don’t have to choose between looks and accessibility. You give your own, clear focus style in :focus-visible, and people clicking with a mouse don’t see an outline on every button they click. Modern browsers’ default outline is also based on this pseudo-class.

Syntax

#
Syntax
selector:focus-visible { property: value; }

Common uses

#
  • button:focus-visible

    Click the button with the mouse: there’s no outline. Now press Tab: it appears, because you’re navigating with the keyboard.
  • button:focus

    For comparison, plain :focus: in most browsers the outline also appears after a mouse click.
  • input:focus-visible

    A text field matches even after a mouse click, because you’re about to type into it on the keyboard.

Common uses in practice

#

button:focus-visible

Click the button with the mouse: there’s no outline. Now press Tab: it appears, because you’re navigating with the keyboard.
button:focus-visible {
  outline: 3px solid #f59e0b;
  outline-offset: 3px;
}

button:focus

For comparison, plain :focus: in most browsers the outline also appears after a mouse click.
button:focus {
  outline: 3px solid #f59e0b;
  outline-offset: 3px;
}

input:focus-visible

A text field matches even after a mouse click, because you’re about to type into it on the keyboard.
input:focus-visible {
  outline: 3px solid #a78bfa;
  outline-offset: 2px;
}

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Don’t write :focus { outline: none }. Browsers already show the default outline only on :focus-visible, and removing it strips orientation from people using a keyboard.
  • Pair hover effects with keyboard focus: .link:hover, .link:focus-visible { 
 }.
  • Pick a focus style that stays visible on any background. A thick outline with outline-offset works better than a subtle color change.

Related entries

#

Spotted a mistake or missing an example? Write to us.