How to Group Form Elements Using Fieldset in HTML
Use the
<fieldset> tag to group related form elements inside a form. Add a <legend> tag inside the <fieldset> to provide a caption describing the group.Syntax
The <fieldset> tag wraps a group of related form controls. Inside it, the <legend> tag defines a title or label for the group. This helps users understand the purpose of the grouped fields.
<fieldset>: Starts the group container.<legend>: Provides a caption for the group.- Form elements like
<input>,<select>, and<textarea>go inside the<fieldset>.
html
<fieldset> <legend>Group Title</legend> <!-- form elements here --> </fieldset>
Example
This example shows a form with two groups: Personal Info and Account Details. Each group uses <fieldset> and <legend> to organize related inputs.
html
<form>
<fieldset>
<legend>Personal Info</legend>
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email">
</fieldset>
<br>
<fieldset>
<legend>Account Details</legend>
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password">
</fieldset>
<br>
<button type="submit">Submit</button>
</form>Output
A form with two boxed groups labeled 'Personal Info' and 'Account Details', each containing related input fields and a submit button below.
Common Pitfalls
Common mistakes when using <fieldset> include:
- Not using
<legend>, which reduces clarity and accessibility. - Placing unrelated form elements inside the same
<fieldset>. - Using
<div>instead of<fieldset>for grouping, which loses semantic meaning.
html
<!-- Wrong: No legend and unrelated inputs grouped --> <fieldset> <input type="text" name="name"> <input type="password" name="password"> </fieldset> <!-- Right: Separate fieldsets with legends --> <fieldset> <legend>Name</legend> <input type="text" name="name"> </fieldset> <fieldset> <legend>Password</legend> <input type="password" name="password"> </fieldset>
Quick Reference
- <fieldset>: Groups related form controls visually and semantically.
- <legend>: Describes the group inside the fieldset.
- Use for better form structure and accessibility.
- Browsers typically draw a border around the fieldset.
Key Takeaways
Use
<fieldset> to group related form elements for better structure.Always include a
<legend> to label the group clearly.Grouping improves accessibility and user understanding of forms.
Avoid mixing unrelated inputs inside the same
<fieldset>.Browsers visually separate groups with a border by default.