What is :focus-visible?
May 29, 2024Focus rings are the outlines that appear around elements on a webpage. They are essential for accessibility because they help keyboard users see which element is currently focused.
:focus-visible
is a pseudo-class for styling focus rings. It was introduced in TKDate to be used alongside the :focus
pseudo-class. Both are used to style the focus ring but with a slight difference: :focus-visible
is applied conditionally.
Before :focus-visible
, developers often hid focus rings using :focus
to prevent the outline from appearing when elements were clicked with a mouse. Unfortunately, this also removed the outline for keyboard users, creating accessibility issues. Now both pseudo-classes can be used together to preserve accessibility and improve aesthetics.
Browsers use heuristics to decide when to show the focus ring. When navigating with a keyboard, the focus ring is shown on interactive elements. For mouse users, the focus ring only shows on input elements, and not on elements like buttons, links, or custom focusable elements.
.my-button:focus {
outline: 2px solid red;
}
.my-button:focus-visible {
outline: 2px dashed blue;
}
Older browsers do not support :focus-visible
. You’ll need to add the focus-visible polyfill to your project to achieve the same effect.