Course contentsShow
← Web Development
Lesson 447 of 2,9828. Advanced CSS Selectors and FeaturesFree lesson

:focus-visible for Keyboard Navigation

Style focus states only when keyboard navigation is used, improving UX for both mouse and keyboard users.

:focus-visible for Keyboard Navigation

You'll learn how to style focus states that only appear when users navigate with a keyboard, creating a better experience for everyone.

The Problem with :focus

When you use :focus, elements show a visible outline whenever they receive focus—whether clicked with a mouse or tabbed to with a keyboard. This creates two issues:

  1. Mouse users see unexpected outlines when they click buttons or links
  2. Designers often remove :focus styles entirely, breaking accessibility for keyboard users

This is like a doorbell that rings loudly whether someone politely presses it or just brushes past it accidentally—annoying for everyone!

The :focus-visible Solution

The :focus-visible pseudo-class solves this by applying styles only when the browser determines the user needs a visible focus indicator—typically when using keyboard navigation.

/* Old way: always shows outline */
button:focus {
  outline: 2px solid blue;
}

/* New way: outline only for keyboard users */
button:focus-visible {
  outline: 3px solid blue;
  outline-offset: 2px;
}

/* Remove default outline for mouse clicks */
button:focus:not(:focus-visible) {
  outline: none;
}

How It Works

The browser automatically detects the input method. When a user tabs through the page with their keyboard, :focus-visible activates. When they click with a mouse, it doesn't.

a:focus-visible {
  background-color: yellow;
  outline: 2px dashed black;
}

input:focus-visible {
  border: 2px solid green;
  box-shadow: 0 0 5px green;
}

Key Takeaway: Use :focus-visible instead of :focus to show focus indicators only when keyboard navigation is detected, improving UX for both mouse and keyboard users without sacrificing accessibility.