Grouping HTML Form Elements
You can use the fieldset element to group related elements within an HTML form. You can also use the legend element to provide a caption for the group.
When you have a long or complex form, breaking it up into smaller, logical sections makes it much easier for users to digest. The fieldset tag draws a visual border around its contents, while the legend tag acts as a title that sits neatly on that border.
Basic Syntax
To use these tags, wrap your related inputs inside a fieldset, and place the legend as the very first element inside it:
Enhancing Accessibility
Grouping elements isn't just about making the form look better. It's also a major win for accessibility. When a screen reader encounters a fieldset, it will often read out the legend before each input inside the group. This helps visually impaired users understand the context of the fields they are filling out.
This is especially important when grouping a list of radio buttons or checkboxes, where a single label isn't enough to explain the entire group.
Full Working Example
In the following example, we use two separate fieldsets to clearly divide the form into "Personal Information" and "Subscription Preferences":