Search code examples
htmlcssscreen-readerssection508nvda

Hide Element but Preserve for Screen Readers (can't use display:none, visibility:hidden, or opacity:0)


I have an audio-element in my HTML whose only purpose is to make an announcement to blind users via a Screen Reader. It's a DIV, but it's invisible to regular users.

The way to announce something is by creating an element with role=alert (no other way to do it, there's no JS function to directly "speak" to a reader, for example):

<!-- This element can be dynamically added OR shown (via JS) to make a Screen Reader announcement -->
<div role="alert">This will be announced to Screen Readers.</div>

However, I can't have this "audio assistant" element be visible to regular users.

1) Can't use display: none; -> the Screen Reader won't pick it up

2) Can't use visibility: hidden; -> the Screen Reader won't pick it up

3) Can't use opacity: 0; -> because space is taken up, layout must be exactly the same

I found this solution: https://stackoverflow.com/a/25339638/1005607

div { position: absolute; left: -999em; }

This works great, it solves my problem. But it's a bit of a hack. I wanted to ask: Is there a better, more standard way to solve this problem?


Solution

  • I'm not sure if this is a "better" way, but this will hide it in place.

    div {
      overflow:hidden;
      height:0;
      width:0;
    }