HTML for Web Development

0% completed

Previous
Next
Grouping Form Elements

In this lesson, you'll learn how to group related form controls together using the <fieldset> and <legend> elements. Grouping enhances both the usability and accessibility of your forms by clearly separating different sections and providing context for the grouped elements.

What Are <fieldset> and <legend>?

  • <fieldset>: The <fieldset> element is used to group related form controls (such as input fields, checkboxes, and radio buttons) together. This makes the form more organized and easier for users to understand.
  • <legend>: The <legend> element provides a caption for the <fieldset>. It describes the purpose of the group and helps users understand the context of the included form elements.

Why Group Form Elements?

  • Organization: Grouping keeps related fields together, making long or complex forms easier to read and navigate.
  • Accessibility: Screen readers use the <fieldset> and <legend> to inform users about the structure of a form. This helps users with disabilities better understand the relationship between fields.
  • Visual Clarity: When styled (even with basic browser defaults), grouped elements are visually separated by a border and caption, improving the overall look of the form.

Syntax for Grouping

The basic syntax for grouping form elements with <fieldset> and <legend> is:

<fieldset> <legend>Group Title</legend> <!-- Form controls for this group go here --> </fieldset>
  • <fieldset>: Encloses the group of form elements.
  • <legend>: Provides a caption that describes the contents of the fieldset.

Example: Grouping Contact Information

Below is an example that demonstrates how to group contact information fields using <fieldset> and <legend>. This group includes fields for a user's name, email, and phone number.

HTML

. . . .

Explanation

  • Personal Details Fieldset:
    • The <fieldset> groups the first name and last name inputs.
    • The <legend> "Personal Details" tells users that the enclosed inputs are related to their personal information.
  • Contact Details Fieldset:
    • A separate <fieldset> groups the email and phone number inputs.
    • The <legend> "Contact Details" clarifies that these inputs are for contacting the user.

Using <fieldset> and <legend> not only makes your forms look better but also ensures they are accessible and easier for users to navigate. Practice grouping different sections of your forms to see how it enhances clarity and usability.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next