<label>

By skvisli for Semantic Advent |

Hi I'm Sondre 👋


As a relatively young React developer, HTML semantics is like an old-forgotten art to me. Fortunately, this advent calendar has provided a fantastic opportunity to increase my understanding of it and embrace the festive learning spirit! 🎄

<label> is used to associate a label with a form control (such as an <input>). It provides a better user experience and accessibility by giving context about the information the form control requests.

Or as summarized by the MDN Docs:

The <label> HTML element represents a caption for an item in a user interface.

Accessibility

Screen readers will announce the label text when the user has focus on the form control. Using the <label> tag will drastically improve accessibility for users.

Pitfall: if you want to style a label, do not use heading elements. This will alter how the assistive technology navigates the web page. Use CSS styling instead.

Clickable area

Clicking the <label> of a form control will pass down focus and events to the form control, creating a larger clickable area. This is very useful for smaller inputs like radio buttons and checkboxes and even more so when supporting touch screens.

Semantics

Using the <label> tag also contributes to the semantic structure of the HTML document and makes the code more readable and better conveys the purpose of the text (It is a label, and it belongs to this form control).

Usage

Okey, are you convinced yet?

Using <label> is a must-have if you want to level up the usability and accessibility of your web forms. But how do you actually use it properly? There are two ways to link your <label> to the form control:

  1. Explicitly: Set the for attribute to the id of the form control you want to associate the label with
<label for="username">Username:</label>
<input type="text" id="username" name="username">
  1. Implicitly: Wrap the form control in the <label> tag
<label>
  Password:
  <input type="text" name="password">
</label>

The code above is also on CodePen

Sign up and receive byte-sized emails about Semantic HTML Elements this advent with real-world use cases!