73 lines
2.5 KiB
Plaintext
Raw Normal View History

A ``++<label>++`` element should wrap a control element or have an ``++<htmlFor>++`` attribute referencing a control and text content.
== Why is this an issue?
When a label element lacks a text label or an associated control, it can lead to several issues:
1. *Poor Accessibility*: Screen readers rely on correctly associated labels to describe the function of the form control. If the label is not properly associated with a control, it can make the form difficult or impossible for visually impaired users to understand or interact with.
2. *Confusing User Interface*: Labels provide users with clear instructions about what information is required in a form control. Without a properly associated label, users might not understand what input is expected, leading to confusion and potential misuse of the form.
3. *Code Maintainability*: Properly structured and labeled code is easier to read, understand, and maintain. When labels are not correctly associated, it can make the code more difficult to navigate and debug, especially for new developers or those unfamiliar with the codebase.
Control elements are:
* ``++<input>++``
* ``++<meter>++``
* ``++<output>++``
* ``++<progress>++``
* ``++<select>++``
* ``++<textarea>++``
=== Exceptions
Custom components may contain control elements, therefore label elements containing custom elements do not raise issues.
== How to fix it
If you have a pair of control and ``++<label>++`` elements, make sure that the ``++<label>++`` wraps the control element.
If you lack a control element, add one.
It is strongly recommended to avoid using generated ``id``s since they must be deterministic.
=== Code examples
==== Noncompliant code example
[source,html,diff-id=1,diff-type=noncompliant]
----
<input type="text" />
<label>Favorite food</label>
----
==== Compliant solution
[source,html,diff-id=1,diff-type=compliant]
----
<label>
<input type="text" />
Favorite food
</label>
----
==== Noncompliant code example
[source,html,diff-id=2,diff-type=noncompliant]
----
<label>Favorite food</label>
----
==== Compliant solution
[source,html,diff-id=2,diff-type=compliant]
----
<label>
<MyCustomInput />
Favorite food
</label>
----
== Resources
=== Documentation
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label[The Label element]
* W3C - https://www.w3.org/WAI/WCAG21/Understanding/info-and-relationships[Info and Relationships]
* W3C - https://www.w3.org/WAI/WCAG21/Understanding/labels-or-instructions[Labels or Instructions]