HTML – Should input elements be inside a label element

Online form fields require two fields – input and label – which work together to describe and collect information.

One question that often comes up is whether to use input elements inside or outside of the label element.

For example:

Separate  – label then input

<label for="lastname">Last Name</label>
<input type="text" id="lastname" />

Separate – input then label

<input type="text" id="lastname" />
<label for="lastname">Last Name</label>

Nested – label then input

<label>
<input type="text" name="lastname" />
Last Name
</label>

Unfortunately, there is no clear consensus on the correct approach.

But in deciding what is best for you, you can consider these points …

Browser compatibility

In terms of browser compatibility, all mainstream browsers support each layout – so compatibility is not an issue.

Accessibility

However, when it comes to accessibility, the answer isn’t as clear – but the general consensus is that “nested – label then input” can improve the accessibility of a form.

This is because it makes it more reliable for screen readers to read the label text for the input element, without having to rely on the “id” and “for” attributes.

This can make it easier for users with visual impairments to use the form.

CSS Styling

With enough patience or skill, each layout is just as easy to format on the page.

However, generally “separate – label then input” is easier as you can cleanly target each element without relying on CSS tricks to get some designs.

Code maintenance

Using a consistent layout is important for code maintainability.

This will become a personal choice for what you feel is best for your projects and/or team – but personally, I prefer “separate – label then input” – and ensure that a valid “id” and “for” is used to link the elements together.

I find it easier to browse and read the HTML when the elements are nested.