How to Use Label in HTML Form for Better Accessibility
Use the
<label> element to describe form inputs by either wrapping the input inside the label or linking it with the for attribute matching the input's id. This improves accessibility and makes clicking the label focus the input.Syntax
The <label> element can be used in two ways:
- Wrapping input: Place the input element inside the label.
- Using for attribute: Use
foron the label with the input'sidto link them.
Both methods connect the label text to the input for better usability.
html
<label for="username">Username:</label> <input type="text" id="username" name="username"> <label>Password: <input type="password" name="password"> </label>
Example
This example shows a simple form with labels linked to inputs using the for attribute and wrapping method. Clicking the label focuses the input box.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Label Example</title> </head> <body> <form> <label for="email">Email:</label> <input type="email" id="email" name="email" placeholder="Enter your email"> <br><br> <label>Phone: <input type="tel" name="phone" placeholder="Enter your phone"> </label> <br><br> <button type="submit">Submit</button> </form> </body> </html>
Output
A form with two fields labeled 'Email:' and 'Phone:' where clicking the labels focuses the respective input boxes.
Common Pitfalls
Common mistakes when using <label> include:
- Not linking the label to the input using
forandid, which breaks accessibility. - Using multiple inputs with the same
id, causing confusion. - Not using labels at all, making forms harder to use for screen readers and keyboard users.
html
<!-- Wrong: label without for and input without id --> <label>Email:</label> <input type="email" name="email"> <!-- Right: label with for and input with matching id --> <label for="email">Email:</label> <input type="email" id="email" name="email">
Quick Reference
| Attribute | Description |
|---|---|
| for | Links the label to an input's id |
| id | Unique identifier for the input element |
| name | Name of the input for form data |
| type | Type of input (text, email, password, etc.) |
Key Takeaways
Always use
Link labels to inputs using the for attribute and matching id.
Wrapping inputs inside labels is a valid alternative method.
Avoid duplicate ids and missing labels to prevent usability issues.