HTML Labels
A label element is a caption that names a form field. Clicking a label moves the focus to its field.
A label beside a field
The label text shows beside the field. Focus means the field is ready for typing.
<label for="fname">First name</label>
<input type="text" id="fname">The for and id pairing
The for value must match the field id. That match links the label to the field.
<label for="fname">First name</label>
<input type="text" id="fname">
<label for="lname">Last name</label>
<input type="text" id="lname">Clicking a label
A click on the word Town lands in the town field. The visitor can start typing at once.
<label for="town">Town</label>
<input type="text" id="town">Example
<!DOCTYPE html>
<html>
<head>
<title>Labels</title>
</head>
<body>
<h1>Sign Up</h1>
<p>Join the cooking class.</p>
<form>
<label for="fname">First name</label>
<input type="text" id="fname">
<label for="town">Town</label>
<input type="text" id="town">
<input type="submit">
</form>
</body>
</html>Key points
- Label: a caption that names one form field
- For attribute: the label setting that holds the field id
- A label names a field, and clicking the label focuses that field.
- Id attribute: the unique name a label points to
- Use one label for each field a visitor must fill
- Screen reader: a tool that reads a page aloud for a visitor
In this example, each field has its own label. The first label has for set to fname. The first field has id set to fname, so the two match. The second label and field match on the name town. A click on either label moves the focus into its field.
Note
A label also helps visitors who use a screen reader.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
How does a label connect to its field?