:focus vs. :focus-visible

It's really important to be able to mark elements as being 'in focus' to aid input devices other than a mouse. It guides the user to let them know where their equivalent of a 'cursor' is.

Try to imagine using Netflix on a Smart TV with a handheld remote control. Without a white line around the actively focused TV show/movie you would be very lost.

Options

There are two ways to mark an interactive element as in focus.

  1. :focus
  2. :focus-visible

Option 1. :focus

This is the older way of doing it and it marks the element as being in focus regardless of the input device.

Whereas…

Option 2. :focus-visible

Only appears when a input device like a keyboard is used. This is usually the preferred option and it’s the way browsers do it in their default stylesheets.

Let’s look at the browser styles for focus:

Blink (Chrome, MacOS)

a:-webkit-any-link:focus-visible {
  outline-offset: 1px;
}

:focus-visible {
  outline: -webkit-focus-ring-color auto 1px;
}

Webkit (Safari, MacOS)

:focus-visible {
  outline-color: -webkit-focus-ring-color;
  outline-style: auto;
  outline-width: 5px;
}

Firefox (MacOS)

:focus-visible {
  outline: 1px auto;
}

All three browsers use :focus-visible and not :focus to style focused elements.

Further reading

  1. MDN - :focus-visible docs
  2. CSS Tricks - :focus-visible
  3. :focus vs :focus-visible

Want to work with us?

Let’s talk about your project