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>
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>
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!