DEV Community 👩‍💻👨‍💻

alex
alex

Posted on • Updated on

Invisible content for screen readers with aria-labelledby

This is more a note for myself than anybody else.

Problem

What if you have a group like the following but for some reason you're not allowed to have a title to tell people what it's for? Maybe your designers think it's contextual enough for sighted people or something.

<div role="radiogroup">
  <input type="radio" id="fish" name="fish">
  <label for="fish">🐟</label>

  <input type="radio" id="mammal" name="mammal">
  <label for="mammal">🧸</label>
</div>
Enter fullscreen mode Exit fullscreen mode

Solution

WebAIM has really good tips on how to hide content from sighted users. I want to focus only on what they say about display: none and visibility: hidden here:

These styles will hide content from all users. The content is removed from the visual flow of the page and is ignored by screen readers. Do not use this CSS if you want the content to be read by a screen reader. But DO use it for content you want hidden from all users.

True. However, Accessibility Developer Guide says:

elements hidden using CSS can still be referenced

How? With aria-labelledby.

Demo

Let do this with our radiogroup example:

<div role="radiogroup" aria-labelledby="hidden-content">

  // Exciting new span!
  <span id="hidden-content">Which animal family do you like better?</span>

  <input type="radio" id="fish" name="fish">
  <label for="fish">🐟</label>

  <input type="radio" id="mammal" name="mammal">
  <label for="mammal">🧸</label>
</div>
Enter fullscreen mode Exit fullscreen mode

The CSS:

#hidden-content {
  display: none;
}
Enter fullscreen mode Exit fullscreen mode

This way, the span is hidden from sighted users but can be read out by screen-readers.

Why not aria-label?

We might ask, why not just apply aria-label to the wrapper div? ADG says: "Text added with aria-label is not searchable in browsers."

The end

🙂

Top comments (0)

🌚 Life is too short to browse without dark mode