HTML & CSS Tip of the Week

The :focus-visible pseudo-class

Published on


Think of :focus-visible as the smarter version of :focus.

It’s basically focus styles with context awareness.

Instead of showing focus rings all the time (like when someone clicks a button), it only shows them when the user is actually navigating with the keyboard.

Here’s how you might use it:

button:focus-visible {
  outline: 2px solid blue;
  outline-offset: 2px;
}

If someone clicks that button with a mouse, they won’t see an outline (because they obviously know where they just clicked). But when someone’s tabbing through your page with a keyboard, then they get that helpful visual indicator!

And you can safely use it on form elements as well, where the focus ring will appear regardless of how a user interacts with it.

Basically, it shows a focus ring when you’d want one, but doesn’t show it when it doesn’t need to, both depending on what the element is, and how as user is interacting with your page.

Dive deeper

If you’d like to dive deeper into the world of focus states, in the video below I look at :focus, :focus-visible, and :focus-within.