DEV Community

Cover image for TIL: HTML <label> elements, what are they `for`?
Unathi Chonco
Unathi Chonco

Posted on

TIL: HTML <label> elements, what are they `for`?

TIL: HTML <label> elements, what are they for?

Today I learnt that <label> elements aren’t just semantic html tags used to make your code a bit more understandable, or “well structured”.

Besides just representing the caption for a specific piece of your interface, labels can give you a few benefits when used correctly to associate the label with an input (or any other labelable element).

There are 2 methods of associating a label to an input

1. Using the for attribute

To get this working you need to:

  • give the <input> an id attribute
  • give the <label> a for attribute that is the same value as the input’s id
<div class="form__group">
  <input class="form__input" type="text" id="name">
  <label class="form__label" for="name">Full name</label>
</div>
Enter fullscreen mode Exit fullscreen mode

2. Having a contained control element

All this requires is placing the input inside of the label, and it will be associated implicitly.

<div class="form__group">
  <label class="form__label">
    <input class="form__input" type="text">
    Full name
  </label>
</div>
Enter fullscreen mode Exit fullscreen mode

Benefits

Accessibility

Assistive tech, such as screen readers, will be able to read out the label when the user is focused on the input. This is a small use-case, but accessibility is always important. A small win that could go a long way.

User Experience

A user, on desktop or mobile, can click on either the input or the label to focus/activate the specific input.

TL;DR and Examples

Labels can be used to activate/focus on an associated input.

Top comments (0)