A little description of the main difference between aria-label
and aria-labelledBy
from my side. 😋
Use aria-label
if label text is not visible on the screen and use aria-labelledBy
if label text is visible.
We can read more on the use cases of both the aria attribute here if we want.
Difference between the usage of label id and aria-labelledby
// first
<label for="username-input">Username</label>
<input id="username-input" />
// second
<label id="username-label">Username</label>
<input aria-labelledby="username-label" />
The first one is a legit or traditional way of associating form labels with inputs. The second one doesn't provide a focus input feature when clicking on the associated label. It is used only for web accessibility. The first one provides not only web accessibility, but also provides the focus input feature. So, we can say that the first one has more power than the second one.
There are two more ways that we can associate labels with input along with the input focus feature.
// Wrapper labels
<label>Username <input /></label>
// Wrapper labels where the label text is in another child element
<label>
<span>Username</span>
<input />
</label>
There is one more way that we can associate invisible or hidden
labels with input but doesn't provide focus input feature.
// aria-label attributes
// Take care because this is not a label that users can see on the page,
// so the purpose of your input must be obvious to visual users.
<input aria-label="Username" />
I have some (my) rules that I use in my workplace.
- I use the first example always whenever it's possible.
- I use
aria-label
when I have don't have visible text. Imagine a form with an input element that doesn't have a label associated with it and placeholder text for giving information on what to put in the input.
- I use
aria-labelledBy
to associated non-label elements with the interactive elements (eg: Input)
Is second one subset of the first one? so is below code invalid pattern since the first one is a superset of second one?
<label id="username-label" for="username-input">Username</label>
<input id="username-input" aria-labelledby="username-label" />
We must know what is the main advantage of associating a label with input. One is you have mentioned in your question that is web accessibility
another one is (ACcording to mdn docs)
You can click the associated label to focus/activate the input, as well as the input itself. This increased hit area provides an advantage to anyone trying to activate the input, including those using a touch-screen device.
From this pattern, you are associating a label with input by two times and one time for the focus input feature. The first one does provide both the feature at the same time so there is no point in adding one more associativity between the label and input.