HTML: One Tag at a Time—Label
Or, you don’t need JavaScript to do that.
Labels are an essential element for creating usable and accessible forms. Unfortunately, many web developers don’t use this valuable tag and will often use span
or p
tags and then use JavaScript to get the same behavior that label
provides natively in the browser.
We use label
in forms as seen in this simple example below:
<form action="">
<label for="search">Search</label>
<input type="search" id="search">
<button type="submit">Search</button>
</form>
Take note of the for
attribute in the label tag of that example. The value assigned to for
is the value of the search input’s id
. This creates an association between the label
and the target input
. A label
associated with a form control allows the user to click on the label to select or bring focus to the target form control. When you use the for
attribute, you are explicitly associating the label with a specific form control.
See it for yourself:
You can also implicitly associate a label with a form control by wrapping the form control with the label
like so:
<form action="">
<label><input type="checkbox" name="commPrefs" id="optEmail"> Opt-in to emails</label>
<label><input type="checkbox" name="commPrefs" id="optText"> Opt-in to SMS</label>
</form>
Labels used this way do not need to have a for
attribute to have the same behavior that explicitly associated ones have.
Label best practices
There are some good “rules of thumb” when comes to using labels in your forms.
First, labels should come before text input fields. Doing this will make your form more accessible.
On the other hand, radio and checkbox controls should precede your labels in your markup (see previous code example).
Finally, labels layout as inline elements so you could potentially have labels that sit next to text input fields unless you style them to force a line break. I won’t go into the debate about whether labels in line with text fields are easier to read versus those that sit above the text fields. I prefer the line break, so that’s what I do.
Conclusion
That’s all I have on labels. Now go impress your web developer friends who keep adding event listeners to meaningless span tags just to focus or select a form control.