Display link outlines only when tabbing
You may know the
:focus
psudo-class,
which is applied when a user focusses on whichever element you’ve extended with
:focus
. It’s commonly used with links, where an outline is drawn around the
focussed link with outline: <style>
and is a very important usability feature
for people who navigate webpages other than with a mouse.
However, when clicking on a link via the mouse, the same display changes applied
under :focus
will flash. This is not so pleasing, and is unnecessary. If a
mouse is being used to click on the link, we don’t need to see elements of
:focus
.
For example, the following will display a dashed outline around a link as well as a colored background. When clicking on the link we will see those elements flash on click.
a:focus {
background-color: var(--focus-color);
outline: dashed;
outline-width: 2px;
outline-offset: 4px;
}
But since 2022 the
:focus-visible
css psudo-class
is supported as standard.
This selector is useful to provide a different focus indicator based on the user’s input modality (mouse vs. keyboard) ~ mdn docs
This means that our page can stay accessible for those who need or want it, while mouse users don’t need to see flashes of UI on each click.
a:focus-visible {
background-color: var(--focus-color);
outline: dashed;
outline-width: 2px;
outline-offset: 4px;
}