This isn't actually as straight forward as you might think.
@cloned gave a great example of why you should have a visible label above an input, it makes it much easier to know what has been filled out.
This is especially important for people with anxiety disorders as they will often recheck everything.
Without a label their only option is delete each field and reenter it (several times) to confirm they have filled everything in correctly.
So the best option is to wrap it in a <label>
(as @cloned suggested) or use <label for="idOfInput">
as an equally valid way of doing it (as you stated in your question).
So what about aria-labelledby
- why would you use this on an <input>
?
Well search boxes are one place where it is widely accepted you can not have a visible label. Using aria-labelledby
is a great way of adding a label to those kind of inputs without having to change an accepted pattern.
But it has a better feature, you can add multiple id's
for an input. This can be great for inputs that are part of a grouping or located in a table (if you have a valid reason to put them in a table) as you can use one label as the group name, one for the item name, making your HTML more DRY (Don't Repeat Yourself).
Why not use aria-label
instead of a aria-labelledby
?
Good question, the main reason is support for aria-label
is still a bit flakey in some screen readers.
Support for aria-labelledby
is better, but still just use a <label>
wherever you can.
tl;dr
Use a <label>
everywhere you can, change the design to accommodate labels if they aren't currently there, even if you have to argue with a graphic designer over the aesthetics of labels.
Use aria-labelledby
everywhere else as it has slightly better support than aria-label
.
Top Tip
'WAI-ARIA' is used to add additional information that cannot be achieved with HTML markup.
Inputs have labels as part of semantic HTML, so use them!
aria-label
and aria-describedby
are only really needed for custom components or labelling things that don't have a native way of doing so (i.e. a clickable region on a page).
WAI-ARIA should be a last resort.