The :focus-visible
pseudo-class applies styles to an element that has received focus and the browser heuristically determines that the focus indicator should be visible (e.g., when navigating with a keyboard). It helps to avoid showing focus styles for mouse users while keeping them for keyboard users.
Example 1: Differentiating Focus Styles
/* Default focus style (for mouse users) */
.my-button:focus {
outline: none;
}
/* Visible focus style (for keyboard users) */
.my-button:focus-visible {
outline: 3px solid #007bff;
}
Explanation
This code removes the outline for mouse clicks but provides a clear, visible outline for keyboard navigation, enhancing accessibility without altering the design for mouse users.
Example 2: Styling Links for Keyboard Navigation
/* Style for a link */
.my-link {
color: #007bff;
}
/* Add a background color on focus for keyboard users */
.my-link:focus-visible {
background-color: #e9ecef;
outline: 2px solid #007bff;
}
Explanation
This ensures that when a user tabs to a link, it gets a distinct background and outline, making it easy to see which link is currently selected. Mouse users will not see this style on click.
Example 3: Custom Checkbox Focus
/* Style for a custom checkbox */
.custom-checkbox:focus-visible {
box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.5);
}
Explanation
For custom form elements that don't have a default focus indicator, :focus-visible
can be used to add a noticeable shadow for keyboard users, improving the accessibility of your custom controls.
Example 4: Focus on a Div with tabindex
/* Style for a focusable div */
.focusable-card {
padding: 15px;
border: 1px solid #ccc;
}
/* Add a border for keyboard focus */
.focusable-card:focus-visible {
border-color: #007bff;
box-shadow: 0 0 5px rgba(0, 123, 255, 0.5);
}
Explanation
When a non-interactive element is made focusable with tabindex
, this ensures a focus style is applied only when it's logically necessary, such as during keyboard navigation.
Example 5: Combining with Other Pseudo-classes
/* Style for a button */
.my-button {
background-color: #6c757d;
color: white;
}
/* Style for hover */
.my-button:hover {
background-color: #5a6268;
}
/* Style for keyboard focus */
.my-button:focus-visible {
outline: 3px solid #6c757d;
outline-offset: 2px;
}
Explanation
This demonstrates how :focus-visible
can be used alongside other pseudo-classes like :hover
to create a comprehensive and accessible user experience for all types of interaction.