legend should be the first child of the fieldset element
Description
The legend
element is used to provide a caption or title for a fieldset
, which groups related form controls. Placing the legend
element as the first child of the fieldset
is crucial for accessibility, as it ensures that screen readers and other assistive technologies correctly interpret and announce the relationship between the legend and the grouped form controls.
Disabilities impacted
- Visual impairments: users with visual impairments who rely on screen readers need the
<legend>
to be correctly positioned to understand the purpose and context of the grouped form controls. - Cognitive disabilities: users with cognitive disabilities benefit from clear and descriptive legends that help them understand the organization and purpose of form controls.
- Motor impairments: users with motor impairments who navigate forms using keyboards or other assistive devices rely on well-structured form elements to interact efficiently.
Why it matters
Ensuring that the legend
element is the first child of the fieldset
improves the accessibility and usability of forms. It helps screen readers correctly associate the legend with the form controls, providing a better user experience for those relying on assistive technologies. This practice also enhances the semantic structure of the HTML, making the document easier to understand and maintain.
Coding problems and solutions
Common coding problems
- Legend not placed first: the
legend
element is not the first child of thefieldset
, causing confusion for screen readers and users. - Missing legend: the
fieldset
element lacks alegend
, leaving users without context for the grouped form controls. - Improper nesting: the
legend
element is incorrectly nested or used, disrupting the semantic structure of the form.
How to fix it
Place the legend as the first child of the fieldset
Ensure the legend
element is the first child of the fieldset
.
Ensure the legend is descriptive
Use descriptive text for the legend
to provide clear context for the grouped controls.
Use proper nesting and structure
Maintain proper nesting and structure to ensure the form is semantically correct.
Known limitations
- Complex forms: for complex forms with multiple
fieldset
elements, ensure each has a descriptivelegend
to maintain clarity. - Styling legends: styling the
legend
element can be challenging due to inconsistent browser support. Ensure styles are tested across multiple browsers. - Screen reader variability: different screen readers may interpret legends and fieldsets differently. Test forms with various assistive technologies to ensure accessibility.
Resources
- MDN Web Docs – <fieldset> element
- MDN Web Docs – <legend> element
- W3C Web Content Accessibility Guidelines (WCAG) 2.1 – Info and Relationships
Rule
- ID:
legend-first-child-of-fieldset