It is used to represent the title of an element in a user interface. This element can be <button>
, <input>
, <meter>
, <output>
, <progress>
, <select>
or <textarea>
.
To associate a <label>
with an element, it can be done in two ways:
- Matching the value of the
for
attribute of the<label>
with theid
attribute of the element.
<label for="name"> Name </label>
<input id="name" name="name" type="text" />
- Putting the element inside the
<label>
itself, in which case thefor
andid
attributes are no longer necessary as the association between both is implicit.
<label>Name<input name="name" type="text" /></label>
Associating a <label>
with an element offers two main advantages:
- The association between the two is not only visual but also programmatic, which means that, for example, a screen reader will be able to read the tag aloud when the user focuses on the element, making it easier for him to understand what data he should enter.
- You can bring the focus or activate the element by clicking on the label in addition to the element itself, which increases the sensitive area and represents an improvement for many users, such as those who use a touch device or who have difficulties with the mouse operation.
It has two attributes:
-
for
: theid
of a form element that supports<label>
and is in the same document. This association occurs with the first of these elements whoseid
is equal to thefor
attribute. If that first element were one that does not support<label>
, the association does not occur and other elements are not considered in the document even if they meetfor
-id
equality. If the<label>
contains an element inside, itsfor
attribute must be equal to theid
of said element. -
form
: theid
of the form to which the<label>
belongs, and which must be in the same document.
Some considerations about accessibility:
-
Do not put interactive elements such as
<a>
or<button>
inside a<label>
, as it makes it difficult for the user to activate the form element associated with the<label>
. - You should not put headings inside a
<label>
, as it can interfere with some types of assistive technology when using headings as a navigation aid. If the<label>
text needs to be adjusted visually it has to be done with CSS. If a form or part of it requires a title, you must use<legend>
within a<fieldset>
. - An
<input type="button">
or<button type="button">
element that has a validvalue
attribute does not need a<label>
to be associated with. Doing so may interfere with how some assistive technologies parse the item.
A form element can be associated with multiple <labels>
.
When a <label>
is clicked and it has an element associated with it, the click
event is also fired on that element.
- Type: inline
- Self-closing: No
- Semantic value: No
Top comments (0)