Fieldsets and Legends in HTML

1. 'fieldset' Element:

The <fieldset> element is used to group related elements within a form. Grouping these elements together can help in organizing complex forms, making them more accessible and easier to understand. It often improves the user experience by visually separating different sections of a form.

2. 'legend' Element:

The <legend> element is used to provide a caption for the content within a ‘<fieldset>‘. The ‘<legend>‘ is typically displayed at the top of the fieldset, giving users a clear understanding of the grouped content.

Basic Syntax:

				
					<fieldset>
  <legend>Caption for the Fieldset</legend>
  <!-- Form elements go here -->
</fieldset>

				
			

Example 1: Grouping Personal Information

				
					<form>
  <fieldset>
    <legend>Personal Information</legend>
    <label for="fname">First Name:</label>
    <input type="text" id="fname" name="fname"><br><br>
    
    <label for="lname">Last Name:</label>
    <input type="text" id="lname" name="lname"><br><br>
    
    <label for="email">Email:</label>
    <input type="email" id="email" name="email">
  </fieldset>
</form>

				
			
  • Fieldset: Groups the personal information fields together.
  • Legend: Provides a caption (“Personal Information”) for the fieldset.

Example 2: Grouping Payment Information

				
					<form>
  <fieldset>
    <legend>Payment Information</legend>
    <label for="card">Card Number:</label>
    <input type="text" id="card" name="card"><br><br>
    
    <label for="expdate">Expiration Date:</label>
    <input type="month" id="expdate" name="expdate"><br><br>
    
    <label for="cvv">CVV:</label>
    <input type="text" id="cvv" name="cvv">
  </fieldset>
</form>

				
			
  • Fieldset: Groups the payment information fields.
  • Legend: Provides a caption (“Payment Information”) for the fieldset.

Styling Fieldsets and Legends with CSS

You can enhance the appearance of 'fieldset' and 'legend' using CSS.

				
					<style>
  fieldset {
    border: 2px solid #4CAF50;
    padding: 10px;
    margin-bottom: 15px;
  }

  legend {
    font-weight: bold;
    color: #4CAF50;
  }
</style>

				
			
  • Border: Adds a green border to the fieldset.
  • Padding: Provides space inside the fieldset.
  • Legend: Makes the legend text bold and green.

Accessibility Considerations

  • Semantic Grouping: The combination of ‘<fieldset>' and ‘<legend>‘ provides semantic meaning, making forms easier to understand for users who rely on assistive technologies like screen readers.
  • Form Organization: Properly grouping form fields can reduce cognitive load and make forms more intuitive.
Scroll to Top