All browsers adopted :focus-visible in their UA stylesheets
- Published at
- Updated at
- Reading time
- 2min
I've had many discussions with folks bothered by focus outlines on link and button clicks. "Can we remove these click lines?" was a sentence I often heard. But, at the time, the :focus
pseudo-class was the only thing we had, and removing focus outlines entirely would break keyboard accessibility. So we had to push back and fight for proper focus outlines!
Luckily, the :focus-visible
pseudo-class helped out. Using :focus-visible
, you could only show outlines when a person navigated links and buttons via the keyboard. Win-win! 💪
But then, a tricky transition period started. How should we work around browsers that don't support the pseudo-class yet? There are two ways.
/*
Enable focus styles if
:focus-visible is not supported
Note: Before using `@supports selector()`
check if its browser support works for you
https://caniuse.com/mdn-css_at-rules_supports_selector
*/
.button {
outline: 0;
}
.button:focus-visible {
outline: 3px solid deepskyblue;
}
@supports not selector(:focus-visible) {
.button:focus {
/* Fallback for browsers without :focus-visible support */
outline: 3px solid deepskyblue;
}
}
/*
Disable outlines if :focus-visible is supported
*/
:focus {
outline: 3px solid deepskblue;
}
:focus:not(:focus-visible) {
outline: none;
}
Today in 2022, though, :focus-visible
is cross-browser supported.
86 | 86 | 86 | 85 | 85 | 15.4 | 15.4 | 14.0 | 86 |
And after reading one of Michelle Barker's articles, I learned that all major browsers removed the standard :focus
outline and went for :focus-visible
instead.
And indeed, when I think about it, I haven't seen click outlines for quite some time.
:focus-visible
still matches focused input
elements, so they always show outlines and work as usual.
I investigated the user agent stylesheets to find out when these changes were applied. Chrome and Firefox adopted :focus-visible
in February 2021 and Safari followed in December 2021.
If you want to look at the default user agent stylesheets. Here they are:
And it's just wonderful; now that :focus-visible
is cross-browser supported, and it made its way into the user agent stylesheets, we don't have to worry about it 99% of the time.
The web developer community requested a feature. Browser makers came up with a solution, which we all happily applied. And then, at a later stage, the browsers adopted the solution so that we don't have to deal with it. I love it!
Join 5.2k readers and learn something new every week with Web Weekly.