Briefly
The for
attribute links the text in a <label>
or a <output>
tag with form controls.
Example
Try clicking on the text in the example below.
<label for="number">Your favorite number:</label><input id="number">
<label for="number">Your favorite number:</label> <input id="number">
The <input>
field becomes active, even though we didnβt touch it. This happens because the text is linked to that field. Thanks to for
, they feel like one whole π
How it's written
The connection is established with a pair of for
-id
attributes, where the for
of one element refers to the id
of another (or others).
Also, not every element is suitable for linking; only those from the category of "linkable":
<button>
;<input>
;<meter>
;<progress>
;<select>
;<textarea>
;- And even the
<output>
itself (/html/output/).
This means that the elements from the above list can have a unique id
that the for
attribute in <label>
or <output>
can refer to.
<input id="name"><input id="age"><output for="name age"></output>
<input id="name"> <input id="age"> <output for="name age"></output>
The values of the for
attribute should not be repeated on the same page. This is because, with it, fields are linked not just visually but programmatically. Thus, users of screen readers and other assistive technologies know what the field is asking from them.
Tips
π‘ The connection between <label>
and <input>
can be established without the for
attribute β it is enough to wrap one within the other:
<label>Your favorite number: <input id="number"></label>
<label>Your favorite number: <input id="number"></label>