Before understanding aria-labelledby it is worth reading aria-label (property). Similar to aria-label, aria-labelledby is also used to provide alternate text for an informative image, label a form element etc. Unlike aria-label, aria-labelledby refers the existing text on the page and uses it as the labelling text. For example If the heading on the page and the image next to it conveys the same information, instead of providing alternate text the content of the heading can be used as the alternate text as shown below.
In the example the heading text Braille Slate is used as the alternate text for the image after it. The label association is maintained using aria-labelledby property and id attribute. Code is shown below.
A similar association can be made for forms and other elements where ever required.
<h3 id=”braille”>Braille Slate</h3>
aria-labelledby=”braille” width=”300″ height=”300″ class=”alignright size-medium wp-image-1031″ />
Combining two labels using aria-labelledby
In some cases a simple piece of text might not be sufficient to add a label or provide an alternate text. Two or more different text from different locations might be required to provide a meaningful label. Using aria-labelledby two different texts can be combined together and used as a single label. As we have used an id reference in the example earlier, more than one id can also be used for the same aria-labelledby property. Provide the id(s) in the order in which the screen reader has to read with a space between them. In the below example, first set of fields are for permanent address, in the next set of fields the billing address is the legend. The labels from the permenent address and the legend from the billing address are combined together to provide a meaningful labels for the form fields.
Below is the code I have used
<legend id=”pa”>Permmnent Address
<label for=”Hno” id=”l1″>House No</label>
<input type=”text” id=”hno” />
<label for=”state” id=”l2″>State</label>
<input type=”text” id=”state” />
<label for=”country” id=”l3″>Country</label>
<input type=”text” id=”country” />
<label for=”zip” id=”l4″>ZIP</label>
<input type=”texxt” id=”zip” />
<legend id=”ba”>Billing Address</legend>
<input type=”text” aria-labelledby=”ba l1″ />
<input type=”text” aria-labelledby=”ba l2″ />
<input type=”text” aria-labelledby=”ba l3″ />
<input type=”text” aria-labelledby=”ba l4″ />
Points to Note
- When visible text is available on the page which can be used for the purpose of a label use aria-labelledby for the reference instead of using aria-label.
- When title or aria-label is used along with aria-labelledby, aria-labelledby takes priority.
- More than one id can be referred for providing a meaningful label.
- Aria-labelledby and aria-describedby works similarly but should be used for different purposes.