How Can You Implement Keyboard-Only Focus Styles Using :focus-visible?

Mary-Kate Olsen
Release: 2024-11-02 20:46:02
Original
277 people have browsed it

How Can You Implement Keyboard-Only Focus Styles Using :focus-visible?

Keyboard-Only Focus Styles in Modern Browsers

In modern browsers, the :focus-visible pseudo class can be utilized to achieve keyboard-only focus styles. This pseudo class matches focused elements when the user interacts with the page via a keyboard or other non-pointing device, indicating focus when it aids the user. As a result, focus rings are suppressed when a user interacts via clicking or tapping.

Custom Focus Styling with :focus-visible

To implement custom focus styles while preserving compatibility with older browsers, follow this approach:

<code class="css">button:focus {
  /* Default focus styles */
}

button:focus:not(:focus-visible) {
  /* Undo default focus styles */
}</code>
Copy after login

Inbrowsers that support :focus-visible, the second rule overrides the focus styles defined in the first rule when :focus-visible is inactive. This ensures that focus styles are only applied when :focus-visible is active.

Original Solution for Older Browsers

For browsers that do not support :focus-visible, an alternative approach involves using an additional element within each focusable element, as proposed in Roman Komarov's article:

<code class="css">/* Root button styling */
.btn {
  all: initial;
  display: inline-block;
}

/* Inner content element */
.btn__content {
  background: orange;
  cursor: pointer;
  display: inline-block;
}

/* Custom focus styles on inner element */
.btn:focus > .btn__content {
  box-shadow: 0 0 2px 2px #51a7e8;
  color: lime;
}</code>
Copy after login

By placing the focus styles on an inner element, while removing default outlines on both the parent and inner elements after adding the custom focus style, only keyboard interactions apply focus styles to the primary visible element.

The above is the detailed content of How Can You Implement Keyboard-Only Focus Styles Using :focus-visible?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template