Basic accessibility for your HTML forms

Today I want to write about a simple, yet powerful element you must include when building an HTML form: labels.

You probably know what a label is. It tells the user what the field is all about. For example, when you see this:

0
An input with a label which says "Name"

You know that you’re supposed to write your name in this input field.

You can write that code in two different ways. This is one option:

Name: <input type="text" />

And this is the second option you have:

<label>Name: </label>
<input type="text" />

For a person who can see, there is no difference. Both pieces of code will display the same on the screen.

But blind users use a screen reader, and without the label tag, they won’t know what the input expects them to write 😕

So now we know that we need to use label tags for every field in our forms. These are the elements that use explicitly associated labels:

  • input type="text"
  • input type="checkbox"
  • input type="radio"
  • input type="file"
  • input type="password"
  • textarea
  • select

But it’s not enough… 🛑

Just because we added a label tag it doesn’t mean our form is ready. We’re missing the most important part, which is associating the label to the input element.

These are the two best ways to do it:

1- Put the input inside the label tag

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

2- Add for attribute on the label and id attribute on the input

<label for="last-name">Last name:</label>
<input id="last-name" type="text" />

The value must be the same for both attributes.

There is a third way of associating a label to the input, which is this one:

<input aria-label="username" />

This works for screen readers, but it removes the visual label from the screen. This is not good because the users won’t know what they are supposed to write in the input.

You may think that adding a placeholder can fix the issue, but only partially. When you type, the placeholder disappears. Once you end filling out the form and you want to check what you wrote, you’ve again the same problem: you don’t know what each field is about.

So it’s better to use one of the first two options. When you successfully associate a label with an input element, the label area becomes clickable as well 🎉 This is a good way to check if you did a good job: click the label and the input should be focused.

A gif showing that clicking the label makes the input focus

One more thing

When you are done building a form, always check if you can fill all the fields by just using your keyboard.

This seems obvious, but a lot of forms (and I mean a lot) are impossible to use without a mouse. You need to think there are lots of people that unfortunately cannot use a mouse, and therefore they won’t be able to fill out your form.

That’s all!

Thanks for reading ❤️