Keyboard-Accessible Pre: A Small, Dependency-Free Script for Making <pre>
Elements Keyboard-Accessible
Because text in a <pre>
doesn't wrap (unless you use something like white-space: pre-wrap
), keyboard-users generally have no means of reading content that overflows the element (except in Firefox).
This little script uses a ResizeObserver to set and maintain the tabindex
of all <pre>
elements on the page, making each of them keyboard-focusable when it has overflow and not keyboard-focusable when it doesn't. When a <pre>
is focusable, it also has generic role
and aria-label
attributes for the benefit of those using a screen-reader (role="group"
and aria-label="Preformatted text that overflows visually"
).