The <label> tag in HTML is used to associate a label with a form control, such as a text input or checkbox. The label text is clickable, and clicking on it will set focus to the associated form control. This can be very helpful for usability and accessibility.
Syntax:
The basic syntax of the <label> tag is as follows:
<label for=”id_of_form_control”>Label Text</label>
The “for” attribute specifies which form control the label is associated with. The value of the “for” attribute should match the “id” attribute of the form control.
Example:
<form>
<label for=”username”>Username:</label>
<input type=”text” id=”username” name=”username”><br><br>
<label for=”password”>Password:</label>
<input type=”password” id=”password” name=”password”><br><br>
<input type=”submit” value=”Submit”>
</form>
In the example above, each label is associated with an input element using the “for” attribute. When the user clicks on the label text, the focus is set to the associated form control. This makes it easier for users to interact with the form.
You can also nest form controls inside label elements. This can be helpful if you want to provide a clickable label for a checkbox or radio button group.
Example:
<form>
<label>
<input type=”checkbox” name=”newsletter” checked> Sign up for our newsletter
</label><br><br>
<label>
<input type=”radio” name=”gender” value=”male” checked> Male
</label>
<label>
<input type=”radio” name=”gender” value=”female”> Female
</label><br><br>
<input type=”submit” value=”Submit”>
</form>
In the example above, the checkbox and radio buttons are nested inside label elements. This makes the label text clickable, which is especially helpful for checkboxes.
Conclusion:
The <label> tag is a simple but powerful tool for improving the usability and accessibility of your HTML forms. By associating labels with form controls, you can make it easier for users to interact with your form and ensure that your form is accessible to everyone, including those who use assistive technologies.