Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Labels and field groups

A field without a label is a puzzle: it is unclear what to type into it. In HTML a label is not just text next to a field but a separate <label> element linked to the field. The link gives you two things at once: clicking the label activates the field, and a screen reader reads the label out when the user reaches the field.

A label with for and id

The for attribute of <label> holds the id of the field the label belongs to:

<label for="email">Email address</label>
<input type="email" id="email">

Click the words "Email address" — the cursor jumps into the field.

A field inside the label

You can nest the field right inside <label>. Then the link appears on its own, and for and id are not needed:

<p><label>Name <input type="text"></label></p>
<p><label>City <input type="text"></label></p>

Both ways are correct. The first one is handier when the label and the field sit in different places in the markup.

Labels for checkboxes

For checkboxes and radio buttons a label matters even more: the box itself is small and hard to hit. With <label> you can click the whole text:

<p><label><input type="checkbox"> Remember me</label></p>
<p><label><input type="checkbox"> I accept the delivery terms</label></p>

A group of fields

<fieldset> combines related fields into a group, and <legend> is the group's title. The browser draws a frame around the group:

<fieldset>
  <legend>Delivery</legend>
  <p><label>Street <input type="text"></label></p>
  <p><label>House number <input type="text"></label></p>
</fieldset>

A group of radio buttons

Most often <fieldset> is needed for radio buttons: each option has its own label, and the whole group has a shared question in <legend>:

<fieldset>
  <legend>Coffee size</legend>
  <label><input type="radio" name="size" value="s"> Small</label>
  <label><input type="radio" name="size" value="m" checked> Medium</label>
  <label><input type="radio" name="size" value="l"> Large</label>
</fieldset>

A screen reader says "Coffee size, Medium" — without <legend> the person would hear only "Medium" and would not know what the question was.

A disabled group

The disabled attribute on <fieldset> switches off all the fields inside at once: they cannot be changed and are not sent:

<fieldset disabled>
  <legend>Gift wrapping (out of stock)</legend>
  <label><input type="checkbox"> Wrap as a gift</label>
</fieldset>

Common mistake

A placeholder does not replace a label. It disappears as soon as the person starts typing — and they can no longer recall what the field was for. Many screen readers do not read it either. Write the field name in <label> and an example value in placeholder:

<label for="phone">Phone</label>
<input type="tel" id="phone" placeholder="+1 202 555 0123">

Thanks for reading!

Donate to the site — we work hard for you.