Focus Indicators and :focus-visible
What you'll learn: How to show focus indicators only when users navigate with a keyboard, avoiding unnecessary outlines during mouse clicks.
The Challenge with Traditional :focus
When you style an element with the :focus pseudo-class, it applies whenever that element receives focus—whether clicked with a mouse or selected via keyboard. This often creates visual clutter: users who click a button with their mouse see an outline they don't need, since they already know where they clicked.
/* Shows outline for BOTH mouse and keyboard */
button:focus {
outline: 3px solid blue;
}
Enter :focus-visible
The :focus-visible pseudo-class is smarter. It automatically detects the user's intent and only shows focus indicators when keyboard navigation is being used. When someone clicks with a mouse, no outline appears. When they tab through with a keyboard, the outline appears where it's needed.
/* Shows outline ONLY during keyboard navigation */
button:focus-visible {
outline: 3px solid blue;
}
/* Remove default outline for mouse users */
button:focus:not(:focus-visible) {
outline: none;
}
The Analogy
Think of :focus-visible like a helpful guide that only appears when you need directions. If you drove directly to a destination (mouse click), you don't need a map marker. But if you're navigating step-by-step through a city (keyboard navigation), that marker becomes essential.
Practical Usage
Most modern designs use :focus-visible to balance aesthetics with accessibility. You keep your interface clean for mouse users while ensuring keyboard users always know their current position—a win-win that respects both visual design and accessibility needs.
Key Takeaway: Use :focus-visible instead of :focus to show indicators only during keyboard navigation, providing necessary feedback without visual clutter for mouse users.