Fieldset and legend
Group form fields with <fieldset> and <legend>.
Grouping fields with fieldset
For long forms, instead of dividing them with <div> you use <fieldset>. This tag pulls related fields into a box; the browser usually draws a border. <fieldset> is especially valuable for accessibility: screen readers read its controls as one group.
To give the group a heading you use <legend>. The legend must be the first child of the fieldset. Its name says it all: it labels groups like a delivery address in shipping or participant details in a survey.
Legend placement and accessibility
The legend must always be the first child of the fieldset; placing it later is invalid. The browser puts the legend at the top-left of the group's frame. The screen reader repeats the heading each time it reads a field, keeping the context clear.
Nested fieldsets are allowed too: in big surveys you split main groups into sub-headings. Going too deep makes a mess; two levels are usually enough.
Exercise Write the delivery address group
Add a <fieldset> to the form. As its first child write a <legend> with the text Delivery address. After the legend add a <label> and an <input>. The label text should be Your address. Set both for and id to adres. Close with </fieldset>.
Show example solution
<form>
<fieldset>
<legend>Delivery address</legend>
<label for="adres">Your address</label>
<input id="adres" name="adres">
</fieldset>
</form>
Test yourself
-
Which statement about fieldset and legend is wrong?
- fieldset brings related fields together
- legend can be placed outside fieldset
- legend appears as the group heading
- legend must be the first child of fieldset
Show answer
legend can be placed outside fieldset — Correct. The legend always sits inside the fieldset as the first child.
-
Write the tag that gives the group a heading
<fieldset><____>Delivery address</legend></fieldset>Show answer
<fieldset><legend>Delivery address</legend></fieldset> -
Match each tag to its role
- fieldset
- Groups related fields
- legend
- Heading for the group
- input
- Draws a data field
- label
- Names the field