DEV Community

Bharathvaj
Bharathvaj

Posted on • Originally published at bharathvaj.me on

Focus vs Focus-Within vs Focus-Visible

Today, we will be discussing focusable pseudo-classes supported by modern browsers, but before we dive deeper, it’s worth understanding what focusable and tabbable means in the context of CSS.

Focusable Element

The element will be focused by the script (element.focus()) and possibly the mouse (or pointer), but not the keyboard.

Tabbable Element

The element will be keyboard focusable (“tabbable”), as it is part of the document’s sequential focus navigation order. Also focusable by the script and possibly the mouse (or pointer).

These pseudo-classes are triggered when the user focuses on an element in different ways.

:focus

Triggered when the user clicks or taps on an element or selects it with the keyboard’s Tab key.



/* Selects any <input> when focused */
input:focus {
  background: yellow;
  color: red;
}


Enter fullscreen mode Exit fullscreen mode

This applies only to the focused element. Here, only the input tag will be highlighted

:focus-within

Triggered when the user clicks or taps on any of its child element or itself



/* Selects a <div> when one of its descendants is focused */
div:focus-within {
  background: cyan;
}


Enter fullscreen mode Exit fullscreen mode

Here if any of that div’s children receive focus that this selector will get applied.

:focus-visible

Triggered by User-Agent on elements having :focus selector based on some heuristics that determine which one of the active elements should receive focus.

This selector is mostly useful to provide a different focus indicator based on the user’s input modality (mouse vs. keyboard).

For instance, let’s say you have <a> tag, you want to remove the focus outline when user focuses it via mouse but want to retain an outline that goes in with the site theme when user focuses via keyboard.



.next-image-button:focus {
  outline: none;
}
.next-image-button:focus-visible {
  outline: 3px solid currentColor; /* That'll show 'em */
}


Enter fullscreen mode Exit fullscreen mode

So, when we use mouse there won’t be any visual outline but with keyboard, there will be a nice visual focus indication that goes along with the site theme.

These CSS pseudo-classes will definitely improve site accessibility when used correctly.

Happy Hacking!!!

Top comments (1)

Collapse
 
krry profile image
Kerry Snyder

Thanks! This was super helpful :D