DEV Community

alex
alex

Posted on • Edited 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

🙂

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay