Course contentsShow
← Web Development
Lesson 1059 of 2,98219. Keyboard Navigation and FocusFree lesson

The :focus-visible Pseudo-Class

Styling focus only when keyboard navigation is detected, improving mouse user experience.

The :focus-visible Pseudo-Class

What You'll Learn

You'll learn how to style focus indicators that appear only when keyboard navigation is used, creating a better experience for both keyboard and mouse users.

The Problem with :focus Alone

When you style elements with the :focus pseudo-class, those styles apply whenever an element receives focus—whether from keyboard, mouse, or programmatically. This means mouse users see focus rings around buttons and links they click, which many find visually distracting since they already know where they clicked.

How :focus-visible Works

The :focus-visible pseudo-class is smarter—it applies styles only when the browser determines the user would benefit from a visible focus indicator. Browsers typically show :focus-visible when:

  • Navigating with the keyboard (Tab, Shift+Tab, arrow keys)
  • The user is interacting primarily through keyboard
  • Text input fields receive focus (even from a mouse click)

But not when:

  • Clicking buttons or links with a mouse
  • Tapping on mobile devices

Think of it like an automatic light sensor: :focus is like a light switch that's always on, while :focus-visible is like a motion sensor that turns on only when needed.

Practical Usage

/* Remove default focus for mouse users */
button:focus {
  outline: none;
}

/* Show focus only for keyboard users */
button:focus-visible {
  outline: 3px solid #4A90E2;
  outline-offset: 2px;
}

This pattern ensures keyboard users always have clear visual guidance, while mouse users don't see unnecessary focus rings cluttering the interface.

Key Takeaway: The :focus-visible pseudo-class provides context-aware focus styling, showing indicators only when users need them for keyboard navigation, creating a cleaner experience for mouse users while maintaining accessibility.