Definition
The <label>
HTML element is used to associate a label with a form control, such as an input element, select element, or textarea element. It improves the accessibility and usability of forms by providing a textual description or name for the associated form control.
Here’s an example of how to use the <label>
element:
<label for="username">Username:</label>
<input type="text" id="username" name="username" />
In this example, the <label>
element is used to associate the label “Username:” with the input field. The for
attribute in the <label>
element specifies which form control it is associated with by matching the id
attribute of the input element. This association allows users to click on the label, which then focuses or selects the associated form control.
Using the <label>
element provides several benefits:
- It improves accessibility by making it easier for assistive technologies to associate the label with the form control.
- It improves usability by providing a larger click area for users to interact with the form control.
- It improves semantics and understanding for users, especially when the label is descriptive and provides context for the form control.
It’s worth noting that the <label>
element can also be used by wrapping the form control inside the <label>
element itself:
<label>
Username:
<input type="text" name="username" />
</label>
In this case, the association between the label and form control is implicit, as the form control is a child of the <label>
element. However, using the for
and id
attributes is generally recommended for better accessibility and compatibility with assistive technologies.