What Does In HTML: Easy Tutorial With Code Example
- Element of
- HTML Web Forms Tutorial For Coding Beginners
- What does
What Does In HTML: Easy Tutorial With Code Exampledo?
- The <label> element is used to associate a text label with a form <input> field. The label is used to tell users the value that should be entered in the associated input field.
<form> <label for="favorite-animal">Favorite Animal</label><br> <input name="favorite-animal" id="favorite-animal"> </form>
Using Labels Properly
<label> element is one of a handful of elements that only exists and makes sense in relationship to another element. In the case of
<label>, the label has to be associated with a form field (usually in
<input> element of one sort or another.
<label> to work properly, it must include a
for attribute, which identifies the
<input> to which it is associated. The
for attribute’s value should match the
id (not the
name) of the
(Form submission relies on
name and label pairing relies on
id. This is why you will often see
<input> elements with the same value in both attributes. And if the
<input> is a checkbox, you might see the same value in the
value attribute, and as the content of the
<label for="first-name">First Name</label><br> <input id="first-name" name="first-name">
<p>Do you agree to the terms and conditions?</p> <input type="checkbox" name="agree" id="agree" value="agree"><label for="agree"> Agree</label>
Labels and Usability
It is, of course, possible to not use the
<label> element, and just put unmarked text over or next to a form field. But this isn’t a good idea. Having a paired label is more than just good semantics, it is good usability. With a properly marked-up label, the user can click (or finger-tap) the label in order to bring focus to the element or select it. This is moderately helpful on regular desktop and laptop computers, but on touchscreen mobile phones, it makes a huge difference.
<!-- With the label --> <input type="checkbox" name="easy" id="easy" value="easy"><label for="easy"> Click this label to select.</label> <br><br> <!-- Without proper labelling --> <input type="checkbox" name="hard" id="hard value="hard"> Can you click this label to select?
Can you click this label to select?
So, aside from basic usability, you also want to be actively working to make your website accessible to the blind and visually impaired — or anyone else who might use a screen reader to browse the internet. The association of the label to the form field allows the screen reader user to know what is obvious to a sighted a user: what words are attached to what form fields.
For more information on this topic, see our tutorial on form usability.
Browser Support for label