<label>

The HTML <label> element links a descriptive text with a form control, enhancing accessibility and usability by clearly identifying the corresponding input field.

<label> Tag

The <label> tag defines text that describes a form element. It improves usability by making forms more accessible, as clicking the label focuses the associated input field.

Syntax

index.html
<label for="id">Label Text</label>
<input type="text" id="id" name="name">
You can nest the <input> inside the <label>, removing the need for the for and id attributes. This automatically links the label to the input.
index.html
<label>
  Do you like coffee?
  <input type="checkbox" name="coffee" />
</label>

Attributes

  • for: Connects the label to an input element by referencing its id, improving accessibility and usability.


index.html
<label for="username">Username:</label>
<input type="text" id="username" name="username">
  • form : Associates the label with a form element outside its parent <form>.
index.html
<label for="email" form="userForm">Email:</label>
<input type="email" id="email" name="email">

Key Points

  • Accessibility: The <label> tag links text to inputs, improving usability for screen readers and allowing label clicks to focus on inputs.
  • Styling: CSS can be applied to the <label> to match form designs.
  • Usability: Using labels ensures that users can easily understand and interact with form elements.

Example Form

Form Example






index.html
<h1>Form Example</h1>
<form>
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" placeholder="Enter your name">
  <br>
  <label for="email">Email:</label>
  <input type="email" id="email" name="email" placeholder="Enter your email">
  <br>
  <label for="message">Message:</label>
  <textarea id="message" name="message" placeholder="Enter your message"></textarea>
  <br>
  <button type="button">Submit</button>
</form>
When an input element is nested inside a <label>, the connection is automatic, eliminating the need for an id and for attribute.

Conclusion

The <label> tag is vital for improving <form> tag accessibility and usability by associating descriptive text with input fields. It enhances user interaction, especially for those using screen readers, and allows users to click the label to focus on the input. Additionally, using <label> makes forms more intuitive and easier to navigate.