"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can You Implement Keyboard-Only Focus Styles Using :focus-visible?

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

Published on 2024-11-07
Browse:222

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:

button:focus {
  /* Default focus styles */
}

button:focus:not(:focus-visible) {
  /* Undo default focus styles */
}

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:

/* 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;
}

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3