Labels
Labels are useful to improve UI (User Interface) and UX (User Experience). By adding a label and linking it with a form component such as a checkbox, users can select the element by clicking the label. It is especially effective when you have a small form component that can be difficult for a user to select.
To create a label, use the <label>
tag. The <label>
tag has an end tag, unlike the <input>
tag. You can add text between the start <label>
tag and the end <label>
tag.
To link a label to a specific input element, use two attributes:
id
in the input tagfor
in the label tag
Use the same keyword to connect those two elements.
Practice
Objective:
Add labels to radio buttons and checkboxes
1. Add new code in the body section of the HTML document
- Open chapter6.html with VS Code (the file used in the previous practice).
- Copy the code for radio buttons and checkboxes created earlier in this chapter.
- Paste the code before
</body>
tag and adjust the code:- add the
id
attribute to the<input>
tag with a unique word for each (you cannot use the same word in the same HTML file), - add
<label>
tags with thefor
attribute using the same word you set in theid
attribute that you want to relate to, and - update the title using the
<h2>
tag.
- add the
<h3>4. Add Labels</h3>
<form>
<h4>Radio Button</h4>
<input id="black" type="radio" name="color" value="black">
<label for="black">Black</label>
<input id="white" type="radio" name="color" value="white" checked>
<label for="white">White</label>
<h4>Check Box</h4>
<input id="black-check" type="checkbox" name="color" value="black">
<label for="black-check">Black</label>
<input id="white-check" type="checkbox" name="color" value="white" checked>
<label for="white-check">White</label>
</form>
After editing the file, make sure that you save it (⌘ + S for Mac, Ctrl + S for Windows).
2. Check the result with a browser
- Open chapter6.html with a browser.
- Now you can select a radio button and checkbox through the labels
You can also check the sample result here (Demo Site).