Search code examples
htmlcssaccessibility

How to make an HTML link displayed as an icon accessible?


I have some links that are displayed only as icons (don't have any text):

<a href="..." class="icon-link"></a>
.icon-link {
  background-image: url(...);
}

How do I make this link accessible for people not accessing the website visually (using screen readers)?

I see few approaches possible, but cannot find any resources on which one is actually right, or best supported:

  • Adding aria-label attribute on <a>
  • Adding title attribute on <a>
  • Adding text inside <a> and then hiding it visually with CSS

Solution

  • Short Answer

    Use visually hidden text.

    Longer answer

    Adding a title offers very little in the way of accessibility. Here is an interesting article on the subject, it links out to further information.

    So with that in mind that leaves option 1 and 3 as viable options, however the best compatibility is using visually hidden text.

    You see support for aria-label is surprisingly low (scroll down the page to the aria-label section), whereas visually hidden text using the example below will cover browsers all the way back to IE6!

    I answered about the most robust way to do visually hidden text (with explanations of why I do each item) in this stack overflow answer. I have copied the same below just for your reference.

    For your use case just add a span within the link with the visually-hidden class.

    .visually-hidden { 
        border: 0;
        padding: 0;
        margin: 0;
        position: absolute !important;
        height: 1px; 
        width: 1px;
        overflow: hidden;
        clip: rect(1px 1px 1px 1px); /* IE6, IE7 - a 0 height clip, off to the bottom right of the visible 1px box */
        clip: rect(1px, 1px, 1px, 1px); /*maybe deprecated but we need to support legacy browsers */
        clip-path: inset(50%); /*modern browsers, clip-path works inwards from each corner*/
        white-space: nowrap; /* added line to stop words getting smushed together (as they go onto seperate lines and some screen readers do not understand line feeds as a space */
    }
    <p>visible text <span class="visually-hidden">hidden text</span></p>

    Added Bonus of visually hidden text

    As @QuentinC pointed out in the comments there is another great reason to use visually hidden text over the other methods.

    If a user uses a browser that does not support CSS (there are still a few text only browsers that people use) then the text will be displayed.