:focus-visible in CSS: What It Is and How to Use It
:focus-visible is a CSS pseudo-class that applies styles only when an element receives keyboard focus, helping to show focus outlines only when needed. It improves accessibility by showing focus indicators for keyboard users but hides them for mouse users.How It Works
The :focus-visible pseudo-class works like a smart highlighter for elements that get keyboard focus. Imagine you are navigating a website using the keyboard's Tab key. When you land on a button or link, :focus-visible lets you see a clear outline or style showing which element is active.
But if you click on the same button with a mouse, the outline won't show. This is because mouse users usually don't need the extra focus highlight, so :focus-visible helps keep the page cleaner and less distracting.
Think of it like a traffic light that only turns green when a pedestrian (keyboard user) is crossing, but stays off for cars (mouse users). This way, the focus indicator appears only when it helps the user navigate.
Example
This example shows a button that gets a blue outline only when focused by keyboard navigation, not when clicked by mouse.
button {
padding: 0.5rem 1rem;
font-size: 1rem;
border: 2px solid transparent;
border-radius: 0.25rem;
cursor: pointer;
}
button:focus-visible {
outline: 3px solid #2563eb; /* bright blue outline */
outline-offset: 2px;
}When to Use
Use :focus-visible to improve keyboard accessibility without distracting mouse users. It is perfect for interactive elements like buttons, links, form inputs, and custom controls.
For example, if you want to keep your site clean but still help keyboard users see where they are, style focus outlines with :focus-visible instead of :focus. This avoids showing outlines when users click with a mouse.
It is especially useful in complex web apps or sites where many elements can be focused, making navigation easier and more user-friendly.
Key Points
:focus-visibleapplies styles only when keyboard focus is detected.- It helps show focus outlines only for keyboard users, improving accessibility.
- Mouse users won’t see focus outlines, keeping the UI cleaner.
- Use it on buttons, links, inputs, and interactive elements.
- Supported in modern browsers and recommended over styling
:focusalone.
Key Takeaways
:focus-visible shows focus styles only for keyboard users, not mouse users.:focus alone.