Chapter 6. Managing Focus
Web pages are keyboard accessible by default because native interactive elements come with the styling and functionality you need to use them out of the box. They are focusable, and they indicate their focus state visually. When you add CSS or especially JavaScript, you must ensure that you maintain that base accessibility or even improve it, and that your custom solutions are accessible as well.
6.1 Provide Focus Styles
Problem
When people access a website using a keyboard, switch device, screen reader, or similar assistive technology, they can use the Tab
key (or a control on another physical device that maps to the key) to jump from one interactive element to another.
If you, as the developer, don’t highlight the currently active item visually using CSS, users can’t orient and navigate.
Solution
Use pseudoclasses to style interactive elements in their focus or focus-visible state, as shown in Examples 6-1, 6-2, 6-3, and 6-4.
Example 6-1. Styling all elements in their focus-visible state
:focus-visible
{
outline
:
0.25em
solid
;
outline-offset
:
0.25em
;
}
Example 6-2. Styling all elements in their focus state
:focus
{
outline
:
0.25em
solid
;
outline-offset
:
0.25em
;
}
Example 6-3. Showing a shadow on video and audio elements if a contained item is currently focused
:is
(
video
,
audio
)
:focus-within
{
box-shadow
:
0
0
10px
3px
rgb
(
0
0
0
/
0
.
2
);
}
Example 6-4. Providing custom focus styles for nonkeyboard users
button
:focus-visible
{
outline
:
0.25em
Get Web Accessibility Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.