dai11y 25/01/2022

Your daily frequent11y newsletter, brought to you by @ChrisBAshton:

Standardizing Focus Styles With CSS Custom Properties

Stephanie Eckles shares a useful snippet for setting your focus styles consistently:

:is(a, button, input, textarea, summary) {
  --outline-size: max(2px, 0.08em);
  --outline-style: solid;
  --outline-color: currentColor;
}

:is(a, button, input, textarea, summary):focus {
  outline: var(--outline-size) var(--outline-style) var(--outline-color);
  outline-offset: var(--outline-offset, var(--outline-size));
}

This applies focus styles to all standard interactable elements, and provides hooks for you to customise parts of the outline style where needed, e.g.

summary {
  --outline-color: lightskyblue;
}

Some designers like to only apply focus styles when an interactable element is tabbed to via keyboard (as opposed to clicked on with a mouse). Stephanie explains how to use the :focus-visible selector to achieve this. The :focus rule above can be swapped± for :focus-visible, and then an outline: none applied when the focussed element is not :focus-visible.

:is(a, button, input, textarea, summary):focus-visible {
  outline: var(--outline-size) var(--outline-style) var(--outline-color);
  outline-offset: var(--outline-offset, var(--outline-size));
}
:is(a, button, input, textarea, summary):focus:not(:focus-visible) {
  outline: none;
}

± whilst browser support for the :focus-visible selector is still gaining traction, Stephanie advises not replacing the :focus rule, but duplicating it instead. Browsers throw out selectors they don’t understand, so we can’t simply join the selectors with a comma (i.e. :is(...), :is(...):focus-visible {}). By maintaining both a :focus and a :focus-visible block, we ensure that browsers that don’t support :focus-visible – but do support CSS custom properties – have visible focus styles. At time of writing, those browsers are Safari and ‘UC Browser for Android’.


Prefer longer newsletters? You can subscribe to week11y, fortnight11y or even month11y updates! Every newsletter gets the same content; it is your choice to have short, regular emails or longer, less frequent ones. Curated with ♥ by developer @ChrisBAshton.

Loading...