Blog post

Improving Website Accessibility: Utilising :focus-within for Keyboard Interaction

Rekha Kumari

-
May 11, 2024
Web Accessibility
CSS
Keyboard
W3c
HTML
Photo by rupixen on Unsplash

The :focus-within CSS pseudo-class matches an element if the element or any of its descendants are focused.

Let’s understand this using an example:

Requirement: In our case, we need the buttons inside a div element with the class actions to receive focus when navigating via keyboard tab press. These buttons are visible upon hovering over the container class, and we want them to be accessible through keyboard interaction.

Please refer to the code below for better understanding.
< div
class = "container" > < div
class = "wrapper" > < div
class = "breadcrumb" > < href = "/johndeo" > Folder </> > < href = "/johndeo" > File </> </ div > < div
class = "actions" > < button
class = "copyLink" title = "Copy link" > <
class = "fa-regular fa-copy" > </> </ button > < button
class = "downloadFile" title = "Download file" > <
class = "fa-solid fa-arrow-down" > </> </ button > </ div > </ div > < div
class = "main" > <> < href = "/title" > :focus-within </> </> <> The :focus-within CSS pseudo-class matches an element
if the element or any of its descendants are focused </> < span > < href = "/johndeo" > By John deo </> | 26 jan, 2024 </ span > </ div > </ div >

Solution: We can utilise the :focus-within CSS pseudo-class by applying it to the parent container class. When the container gains focus, we set the visibility of the actions class to visible, allowing the buttons to appear on the screen and receive focus in the expected order, as they are interactive elements.

.container {
width : 400px ;
border : 1px solid black;
padding : 10px ;
margin-bottom : 5px ; }
.actions {
display :flex;
justify-content :space-between;
width : 60px ;
visibility :hidden; }
.container :hover .actions {
visibility :visible; }
.container :focus -within .actions {
visibility :visible; }
.wrapper {
display :flex;
justify-content :space-between; }
button {
cursor :pointer; }
span {
color :grey; }

Conclusion: This pseudo-class in CSS improves accessibility and user experience by applying styles when any part of an element or its children is in focus.

That’s all for today.

I hope it was helpful. Give them a round of applause by clicking the 👏 button below. Your feedback means a lot to me!

Thanks for reading.

I’m Rekha(Frontend Engineer), I write about frontend and accessibility. Stay tuned for more insights! 🙌
LinkedIn

Related Blog Posts