Search code examples
htmlaccessibility

ARIA Labels in HTML: Inside or Outside the Element?"


I'm working on improving the accessibility of my website and have a question regarding the placement of ARIA labels in HTML. When using ARIA attributes like aria-label or aria-labelledby, is it considered best practice to place them inside the element they are labeling or outside? For instance, which of the following is the recommended approach:

<div class="container" aria-label="testing">
  <input type="text" />
</div>

OR

<div class="container">
  <input type="text" aria-label="testing" />
</div>

Thanks


Solution

  • The correct answer is your second example. The first one won't work.

    The attribute aria-label must be put on the element you are labelling. Putting it in another element has no effect. Labelling elements with aria-label only work if the element is interactive and focusable, or if it has an explicit role assigned. This is the case of input fields and links, but not <div> in the normal case.

    The attribute aria-labelledby works the same as aria-label, except that it refers to another element containing the label, instead of giving a label dirrectly. It also has the same limitations.

    For similarity as how native <label> works, it's better to place the labelling element before or after the labelled element, but not as a parent. In other words:

    <label for="X">...</label>
    <input id="X"/>
    

    Works better than:

    <label>...
    <input/>
    </label>
    

    So similarly,

    <div id="X">...</div>
    <input aria-labelledby="X"/>
    

    Works better than:

    <div id="X">...
    <input aria-labelledby="X"/>
    </div>
    

    IN this later case, it's possible that the label is read twice.

    If you have the possibility to do so, though, it would be much better to use a real <label> element instead of aria-label or aria-labelledby attributes. The first rule of ARIA says that you shouldn't use ARIA if you can do it simpler in another way, and in this case using native <label> is a very easy solution to not use ARIA. Attributes aria-label and aria-labelledby should be used only when it's not very practical to have a <label>.

    Remember that <label> give a bonus feature for free, the possibility to click on it to focus the element it is attached to. It may look a bit useless for you, but it's in fact extremely important for partially sighted people, or those who have imprecise hand movements, for example.