DEV Community

Cover image for Hiding content for accessibility
Alvaro Montoro
Alvaro Montoro

Posted on

Hiding content for accessibility

Hiding content in an accessible way is key for Web Accessibility, and it is not as trivial as it may seem.

There are different ways to hide parts of a webpage using HTML and CSS:

  • The hidden attribute.
  • Using display: none.
  • Using visibility: hidden.

But they completely hide the content, and there are cases in which it is convenient to have content visually hidden yet still accessible for screen readers and assistive technologies.

Jonathan Snook shares different ways to achieve accessible hiding. We can combine some of them together, although it may be an overkill:

.a11y-hidden {
  position: absolute;
  left: -1000in;
  top: auto;
  height: 0px; 
  width: 0px; 
  overflow: hidden;
  clip: rect(0px, 0px, 0px, 0px); 
}
Enter fullscreen mode Exit fullscreen mode

With that code, we will be able to visually hide content on a web page, that will still be accessible for assistive technologies like screen readers. This will be convenient for elements like a "Skip to content" link or additional text in links and buttons (e.g. to avoid the "Read more" only link text.)

The interactivity exception

While it is nice to have a way to hide content only visually, it is important to note that this content may need to become visible in some cases like when getting focused (especially if the content is interactive).

A great example of this is the "Skip navigation"/"Skip to content" link that is common in many web pages: we want the link to be hidden most of the time but visible when it gains focus, so sighted users are not confused about where the focus went.

To do that, we can introduce a second class that "resets" the styles that hid the element in the first place. The properties of this class will depend on the method used to hide the content. In our case:

.a11y-focusable:focus {
  position: initial;
  height: auto;
  width: auto;
  left: auto;
  clip: auto;
  overflow: auto;
}
Enter fullscreen mode Exit fullscreen mode

Note: for some elements, you may want to keep the position: absolute so the page doesn't shift when hiding/showing the content.

In the case of the "Skip to content" link, we could have something like this:

<style>
.a11y-hidden {
  position: absolute;
  left: -1000in;
  top: auto;
  height: 0px; 
  width: 0px; 
  overflow: hidden;
  clip: rect(0px, 0px, 0px, 0px); 
}

.a11y-focusable:focus {
  position: initial;
  height: auto;
  width: auto;
  left: auto;
  clip: auto;
  overflow: auto;
}
</style>

<a href="#main" class="a11y-hidden a11y-focusable">
  Skip to main content
</a>
Enter fullscreen mode Exit fullscreen mode

Provide a way to visually hide content while still making it accessible to assistive technologies.

Top comments (1)

Collapse
 
ziizium profile image
Habdul Hazeez