:focus-visible CSS Pseudo Class

Description

The :focus-visible pseudo-class in CSS is used to apply styles to an element when it receives focus only if the user is interacting with the page using a keyboard or other non-pointer input method (e.g., a screen reader or voice command). This pseudo-class is particularly useful for improving the accessibility and usability of web applications.

The :focus-visible pseudo-class helps prevent unnecessary styles from being applied when a user clicks on an element with a mouse or taps on it with a touchscreen device, as these actions don't necessarily indicate keyboard-based navigation or focus. By applying styles only when focus is achieved through keyboard interaction, developers can create a more seamless and intuitive user experience for all users, including those with disabilities.

Here's an example of how :focus-visible can be used in CSS:

/* Apply styles to an element when it receives focus via keyboard */
button:focus-visible {
outline: 2px solid blue;
background-color: yellow;
}

/* Apply a different style when focused with any input method (including mouse) */
button:focus {
outline: none;
background-color: lightgray;
}

In this example, the button will have a blue outline and a yellow background only when it receives focus through keyboard interaction, ensuring that the focus styles are visible and helpful to keyboard users while not interfering with mouse or touch interactions.

Syntax

:focus-visible {
  /* ... */
}

Example

<input type="text" value="Default styles" /><br />
<button>Default styles</button><br />

<input class="focus-only" type="text" value=":focus" /><br />
<button class="focus-only">:focus</button><br />

<input class="focus-visible-only" type="text" value=":focus-visible" /><br />
<button class="focus-visible-only">:focus-visible</button>
input,
button {
margin: 10px;
}

.focus-only:focus {
outline: 2px solid black;
}

.focus-visible-only:focus-visible {
outline: 4px dashed darkorange;
}

Browser Support

The following table will show you the current browser support for the CSS :focus-visible pseudo class.

Desktop
Edge Chrome Firefox Opera Safari
8686857215.4
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview
86856115.41486

Last updated by CSSPortal on: 1st October 2023