In order to implement accessible hidden content using CSS, it’s best to use an up to date method. In the past developers would hide content with CSS using various impractical and questionable methods. Let’s consider a better way to hide content with CSS.
The idea behind accessibly hidden text with CSS is that you want to accomplish two things:
- Hide the content visually from most users
- Allow the content to be accessible by users with assistive devices such as screen readers
Here is the CSS code to apply to accessibly hide content:
.sr-only:not(:focus):not(:active) {
clip: rect(0 0 0 0);
clip-path: inset(50%);
height: 1px;
overflow: hidden;
position: absolute;
white-space: nowrap;
width: 1px;
}
Code language: CSS (css)
With this in your stylesheet, you can use the .sr-only
class in your HTML. Simply apply the class to any element you want to be hidden from the majority of users while remaining accessible to screen reader users.
A full explanation of the code can be found in this article by Scott O’Hara where he covers the different ways to hide things in HTML and CSS.