Search code examples
htmlaccessibilitycss-tableswai-aria

How to Rename a Table Header Element With Aria


I have a table with a table header structure as follows. The last four column headers have the same name, as there is a photo appended above that adds contextual value. However, for screen reader accessibility, I want to have the screen reader say a different name for the last four table headers, which would help provide additional context to what the photos do. Currently, it just says "Title" but I would like to add context to make the screen reader say something like "Title This", "Title That", "Title whatever", etc.

I have tried adding title="", aria-labelledby="", aria-label="", to the 'th' elements and none have seemed to work. Also, I do not want to change the actual name that is displayed for each column header.

 <th class="text-right text-dark">Name Title</th>
 <th class="text-center text-dark" name="name 1">Title</th>
 <th class="text-center text-dark" name="name 2">Title</th>
 <th class="text-center text-dark" name="name 3">Title</th>
 <th class="text-center text-dark" name="name 4">Title</th>

Any thoughts or suggestions are apprecieated!


Solution

  • You're not going to be able to use aria attributes to override the innerText of a table header element -- at least not reliably and consistently.

    The reason for this is that the spec for the accessible name computation is poorly defined, so assistive technologies all do their own interpretation of how to handle aria-label, aria-labelledby and aria-describedby. You could make it work in JAWS, but not NVDA or Voiceover, so it will never be consistent.

    Here's a testing page that outlines how each screen reader handles these aria attributes. In my limited testing using NVDA, I found the results to be accurate even though they are a couple of years old.

    You might be better off doing something like this:

    <!-- HTML -->
    <th>
        <span aria-hiddden="true">Text invisible to screen readers</span>
        <span class="sr-only">Text just for screen readers</span>
    </th>
    
    <!-- CSS -->
    <style>
    .sr-only {
        clip: rect(1px, 1px, 1px, 1px);
        clip-path: inset(50%);
        height: 1px;
        width: 1px;
        margin: -1px;
        overflow: hidden;
        padding: 0;
        position: absolute;
    }
    </style>
    

    The problem with the above approach is that you would be offering different content to users of assistive technology as opposed to everyone else. While that's not necessarily bad, you should definitely have a very good reason for wanting to do that that goes beyond stylistic or design choices.