Recently I've been hearing to avoid "implicit" labels and to favor explicit labels for accessibility reason. This was the story I was given, but it felt like there was something missing from the story.
<!-- Implicit -->
<label>
Text
<input>
</label>
<!-- Explicit -->
<label for="example">Text</label>
<input id="example">
After doing some research I found, like with all things, there is some more nuance to the story.
- Both are 100% fine and completely valid according to all language and accessibility specifications.
- HOWEVER, specs and real world implementations are two different things. Some actual screen readers do in fact have problems reading labels properly.
- The issue is not related to the code being nested in a label, but instead whether there is an
id/for
attribute involved.
Sources:
- Screen reader benchmark testing:
TLDR:
<!--
Bad: Though all screen readers *should* work with this,
some just won't play nice with it.
-->
<label>
Text
<input>
</label>
<!--
Works: This has the same support in screen readers as
the next option, but semantically it's not great, as the
label header contains non-text content
-->
<label for="example">
Text
<input id="example">
</label>
<!--
Best: This separates the label tag and input so their
duties are not conflated, it uses the for/id attributes
that works in all screen readers
-->
<label for="example">Text</label>
<input id="example">
And of course, make sure to use unique ID's.
Top comments (1)
Good stuff! I was looking for a succinct explanation for this scenario. Thanks for the research!