MakeW3web

Labels

Labels in HTML are used to provide a textual description for form elements, such as input fields, checkboxes, and radio buttons. They enhance the usability and accessibility of a form by making it clear what information is expected from the user.

Labels are created using the `<label>` element, which is typically placed next to the form control it describes. To associate a label with a specific form control, you should use the `for` attribute on the `<label>` element, and its value should match the `id` attribute of the associated form control.

Here are some examples of using labels with various form elements:

  1. Text input field:
<label for="username">Username:</label>
<input type="text" name="username" id="username" placeholder="Enter your username">

  1. Password input field:
<label for="password">Password:</label>
<input type="password" name="password" id="password" placeholder="Enter your password">

  1. Radio buttons:

<label for="male">Male</label>
<input type="radio" name="gender" id="male" value="male">

<label for="female">Female</label>
<input type="radio" name="gender" id="female" value="female">

  1. Checkboxes:

<label for="terms">I agree to the terms and conditions</label>
<input type="checkbox" name="terms" id="terms" value="agree">

  1. Select dropdown:

<label for="country">Country:</label>
<select name="country" id="country">
  <option value="usa">USA</option>
  <option value="canada">Canada</option>
  <option value="uk">United Kingdom</option>
</select>

Using labels in your HTML forms not only improves the user experience but also enhances accessibility for users with screen readers or other assistive technologies. When a user clicks or taps on a label, the associated form control gains focus, making it easier to interact with the form on touch devices or with a mouse.

Was this page helpful?