Welcome to this tutorial on 'Label Implementation'. The purpose of this tutorial is to teach you how to associate labels with form controls, which is a crucial skill in creating accessible forms for all users, including those leveraging assistive technologies.
By the end of this tutorial, you will be able to:
- Understand the importance and usage of labels in HTML forms
- Learn how to associate labels with different form controls
- Apply best practices for label implementation
Prerequisites: Basic knowledge of HTML and understanding of form controls in HTML.
Label tags in HTML are used to provide a text description to form controls. These are particularly useful for users who rely on screen readers. There are two ways to associate a label with a form control.
for
attribute in the label tag and associate it with the id
of the form control.for
attribute in the label tag matches with the id
of the form control.<label>Username:
<input type="text" name="username">
</label>
This creates a text input field with the label "Username". Here, the label is implicitly associated with the input field by wrapping the input tag within the label tag.
<label for="username">Username:</label>
<input type="text" id="username" name="username">
In this case, the label is explicitly associated with the input field by using the for
attribute in the label tag, which corresponds to the id
attribute of the input tag.
In this tutorial, we learned about label implementation and how to associate them with form controls for better accessibility. We also explored implicit and explicit ways to achieve this association.
Exercise 1: Create a form with two input fields: 'Username' and 'Password'. Use implicit association for the labels.
Solution:
<form>
<label>Username:
<input type="text" name="username">
</label>
<label>Password:
<input type="password" name="password">
</label>
</form>
Exercise 2: Now, modify the form created in Exercise 1 to use explicit association for the labels.
Solution:
<form>
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<label for="password">Password:</label>
<input type="password" id="password" name="password">
</form>
Tips for further practice: Try associating labels with other form controls like checkboxes, radio buttons, etc.