DEV Community

Mihaela Miches
Mihaela Miches

Posted on

Labelling form inputs

Semantic HTML and accessibility

Most of the times, when it comes to HTML and accessibility, all boils down to semantic HTML, that is using the correct HTML elements for their purpose as much as possible. This ensures that screen readers can infer as much information about the intent behind your page structure and announce the content in a meaningful way for the users.

Going the extra mile

There are scenarios where you'll need to put extra work to make sure the content is accessible to everyone. An instance of this are form inputs and their associated labels.

Let's take as an example a text input:

<input type="text"/>

All users, whether they're using a screen reader or not will have a hard time figuring out what information are they supposed to enter in the input. The natural thing is to add a label next to the input:

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

That gives context to sighted users but is not of much help when we use a screen reader. Voice over is not able to infer the context in which we use the input.

Let's make it clear for the screen readers:

<label for="first-name">First Name:</label>
<input id="first-name" />

The input element is identified by an id which we can use to tell the label to which element it's associated using the for attribute.

Other methods of labeling form controls

Using the for attribute to associate a label with the form control is not the only way to achieve accessible form controls.

Just as well, you could set the aria-labelledby attribute to the id of the label

<label id="first-name">First Name:</label>
<input aria-labelledby="first-name" type="text"/>

Using an aria-label attribute or wrapping the input element by a label will also do the job.

Top comments (1)

Collapse
 
caiobessa profile image
caiobessa

Thanks for the explanation. What screen reader do you use to test your application?