The <legend> Element
As defined in the HTML Living Standard, the <legend> element represents a caption for the rest of the contents of the element's parent <fieldset> element.
<fieldset>
<legend>Shipping Method</legend>
<!-- inputs go here -->
</fieldset>
View HTML Living Standard: The legend element
Strict Hierarchy
To be semantically valid, the <legend> element must follow specific placement rules:
- Parent: It must be a direct child of a
<fieldset>element. - Order: It must be the first child of that fieldset.
- Quantity: Only one
<legend>is permitted per fieldset.
WCAG Requirement: Info and Relationships
Success Criterion 1.3.1 (Level A): Information, structure, and relationships conveyed through presentation can be programmatically determined.
The <legend> acts as the programmatic "label" for the group of controls. When a screen reader user enters the fieldset, the browser announces the legend text before the first input's label. This provides the context necessary to understand individual choices (e.g., distinguishing "Standard Shipping" for a Method choice vs. a Carrier choice).
Styling Challenges
The <legend> element is notoriously difficult to style consistently across browsers due to legacy rendering rules that place it "on" the border of the fieldset.
- Spacing: Use
paddingon the legend itself to create space around the text, but usemarginon the fieldset to control layout. - Modern Reset: Many developers choose to visually hide the border of the fieldset and use the legend simply as a semantic group header.
A11y Tip: Clarity over Style
While you can style the <legend> to look like a standard heading, ensure it remains distinct enough for users to perceive it as a label for the following group of inputs. Always ensure high contrast (WCAG SC 1.4.3) for legend text.