What does <label> do? How does <label> link to an input field?
The <label> element is used to create a caption for a form element (for example, for <input>, <select>, <textarea>).
It makes the interface more convenient and clearer: the user sees which field the text belongs to, and can click the caption to activate that field.
1. Basic usage example
<form>
<label for="email">Your email:</label>
<input type="email" id="email" name="user_email">
</form>What happens:
<label>contains the text "Your email:";- the
for="email"attribute indicates which field this label is linked to; id="email"on the field is the identifier thatforrefers to.
Result: clicking the text "Your email" automatically moves focus into the input field.
2. How the link works
The link between <label> and a form element happens through the for attribute and the id value.
What <label> has | What the form element has |
|---|---|
for="email" | id="email" |
Diagram:
<label for="username">Username:</label>
<input type="text" id="username" name="user">The <label> is "attached" to the field with id="username".
3. Alternative approach: without for
You can simply nest the input element inside <label>.
Then the link is established automatically:
<label>
<input type="checkbox" name="agree">
I agree to the terms
</label>Here, clicking the text also activates the checkbox.
This approach is convenient for short captions (checkbox, radio).
4. Why
- Improves usability: clicking the text can activate the field, convenient on mobile.
- Increases accessibility: screen readers announce the
labelas the user navigates through the form. - Improves form clarity: the text and the field are visually linked.
- Requires no JavaScript; it all works at the HTML level.
5. Examples for different fields
Text field:
<label for="name">Name:</label>
<input type="text" id="name">Radio buttons:
<label>
<input type="radio" name="gender" value="male">
Male
</label>
<label>
<input type="radio" name="gender" value="female">
Female
</label>Checkbox:
<label>
<input type="checkbox" name="agree">
I accept the terms
</label>Summary:
| Element | Purpose |
|---|---|
<label> | Caption for a form element |
for | Indicates which element the label is linked to |
id on the field | Must match for |
| Alternative | The field can be nested inside <label> |
| Benefit | Improves accessibility, clickability and convenience |
In simple terms:
<label> is a tag for a field.
It tells the user: "type it in here",
and the browser: "link this text to a specific form element".
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.