Dan Fabulich
Dan Fabulich

Reputation: 39593

Use aria-label on a span

I'm showing product ratings using Unicode star symbols. iOS VoiceOver doesn't read this aloud correctly, so I thought I'd use aria-label on my span to tell screen readers what it means.

<span aria-label="4.0 stars out of 5, 123 ratings">★★★★☆ 4.0 (123)</span>

It's not working. iOS VoiceOver ignores my aria-label completely.

What am I doing wrong? How can I fix this?

Upvotes: 14

Views: 31387

Answers (3)

Abdull
Abdull

Reputation: 27862

Quoting mdn web doc's aria-label article:

Not all elements can be given an accessible name. Neither aria-label nor aria-labelledby should be used with non-interactive elements or inline structural role such as with code, term, or emphasis nor roles whose semantics will not be mapped to the accessibility API, including presentation, none, and hidden. The aria-label attribute is intended for interactive elements only.

So that's why aria-label has no effect on <span> elements: <span> is a non-interactive element without semantics.

But here is what you can do: provide two <span>s, each expressing the same information but for separate "target groups":

  • One <span> is the visual no-screenreader version; the attribute aria-hidden="true" will make sure it will not be part of the accessibility tree and therefore not be communicated by screen readers to their users.
  • One <span> is the accessible screenreader version: CSS styling takes care of visually hiding it.

Reusing Bootstrap 5's .visually-hidden CSS class, your example can be rewritten like so:

.visually-hidden {
    position: absolute !important;
    width: 1px !important;
    height: 1px !important;
    padding: 0 !important;
    margin: -1px !important;
    overflow: hidden !important;
    clip: rect(0,0,0,0) !important;
    white-space: nowrap !important;
    border: 0 !important;
}
<span aria-hidden="true">★★★★☆ 4.0 (123)</span>
<span class="visually-hidden">4.0 stars out of 5, 123 ratings</span>

  • Visually, this will only present "4 black Unicode stars, 1 white Unicode star, 4.0, and 123 in parentheses".
  • For screen readers, this will only present "4.0 stars out of 5, 123 ratings".

Upvotes: 6

slugolicious
slugolicious

Reputation: 17563

The aria-label is sometimes ignored by some assistive technology if the element you put it on doesn't have any semantic meaning. A <span> doesn't have semantic meaning. If you add a role that is appropriate for your stars, then it should be read correctly.

Upvotes: 18

Steve Faulkner
Steve Faulkner

Reputation: 2640

One method would be to add a role=img

<span aria-label="4.0 stars out of 5, 123 ratings" role="img">★★★★☆ 4.0 (123)</span>

Upvotes: 4

Related Questions