One Quick Trick to Up Your Website’s Accessibility

Katie King
2 min readJun 28, 2020

--

We can all agree labels make our inputs more semantic and accessible. Who doesn’t love clicking on a label’s text to immediately focus inside the input?

But there’s a detail regarding input and labels that we haven’t yet made up our collective mind about. A detail that has implications for user accessibility as well as developer readability:

To nest, or not to nest?

Here’s an example of the typical label and input setup I learned in the beginning:

As you can see, the label and input are sibling elements, linked by the “for” and “id” attributes. This works perfectly well, but there is another option. Behold:

But what about those “for” and “id” attributes? Don’t we need them in order for the labels to be clickable?

Nope! You can omit them and retain exactly the same functionality.

Sit tight, though, because there’s a catch: while you absolutely can omit “for” and “id,” you probably shouldn’t.

The reason is accessibility. Nesting your inputs is great for accessibility, but why not cover all your bases? For optimal accessibility, nest your inputs inside your labels and include appropriate “for” and “id” labels. That way, you get the accessibility benefits of both methods.

Boom! That there input is super extra extremely accessible.

In addition to the accessibility benefits, it’s my opinion that nesting our inputs in the above manner is simply more readable, especially for larger forms. No longer will your eye have to hunt for two separate attributes, leaving you to make that logical connection on your own. Why not save your brain that millisecond of searching? The less we have to pause and think about the little things, the more energy we have to tackle the truly interesting problems.

A little gotcha to keep in mind: if you want the labels to be hidden from sighted users for design purposes, adding a class of “sr-only” or equivalent will hide the input as well. Some creative CSS manoeuvoring may be in order for those cases.

--

--