I have learned my fair share about the importance of keyboard accessibility, so I know that visual indication of the focused element is very important. But the well-known :focus pseudo-class is not always the best fit for this job. That's where :focus-visible comes in. Let's look at the differences between these two pseudo-classes and explore the best practices for using them effectively.
The :focus pseudo-class is a CSS selector that applies styles to any element that receives focus, regardless of how that focus was triggered. This includes focus events from keyboard navigation, mouse clicks, and touch interactions.
button:focus { outline: 2px solid blue; }
In this example, the button will display a blue outline whenever it is focused, whether the user clicks on it with a mouse, taps it on a touchscreen, or navigates to it using the keyboard.
The :focus-visible pseudo-class is more specialized. It only applies styles to an element when the browser determines that the focus should be visible. This typically occurs when the user navigates via the keyboard or assistive technologies rather than through mouse or touch input.
button:focus-visible { outline: 2px solid blue; }
Here, the button will only show a blue outline when focused through keyboard navigation or another input method that usually requires visible focus indicators.
To achieve the best accessibility and user experience, combining both :focus and :focus-visible in your CSS is often a good idea.
button:focus { outline: 2px solid blue; }
Here is a Stackblitz example of what such styling could look like for you to try out and play with:
The :focus-visible pseudo-class offers a more refined way to manage focus indicators, improving accessibility and user experience, particularly for keyboard and assistive technology users. By understanding the differences between :focus and :focus-visible, and applying best practices in your CSS, you can create more accessible and user-friendly web applications.
Remember, accessibility should never be an afterthought. By thoughtfully applying focus styles, you ensure that all users, regardless of how they interact with your site, can easily navigate and interact.
The above is the detailed content of Understanding the Difference Between `:focus` and `:focus-visible` in CSS. For more information, please follow other related articles on the PHP Chinese website!