Introduction
The <fieldset>
element in HTML is used to group related elements within a form and create a visual separation or a border around them.
It is often used in conjunction with the <legend>
element, which provides a title or caption for the group of form controls enclosed by the <fieldset>
.
Here is an example :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form>
<fieldset>
<legend>Contact Information</legend>
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br>
<!-- Additional form controls can be included here -->
</fieldset>
<!-- Other form elements can be outside the fieldset -->
<input type="submit" value="Submit">
</form>
</body>
</html>
Output :
In this example, the form controls for “Name” and “Email” are grouped within a <fieldset>
, and the <legend>
element provides a title (“Contact Information”) for that group. The <fieldset>
helps to visually organize and group related form elements, making the form more accessible and user-friendly.
Key points about the <fieldset>
element:
- Visual Grouping: It is commonly used to group related form controls together and visually separate them from other parts of the form.
- Accessibility: It improves the accessibility of the form by providing a semantic grouping for assistive technologies. Screen readers can announce the legend text to provide context to users.
- Styling: Developers can apply styles to the
<fieldset>
to enhance the visual appearance of the grouped form controls. - Form Organization: It’s particularly useful when a form has multiple sections or categories of information.
- Use with
<legend>
: The<legend>
element is often used inside a<fieldset>
to provide a title or description for the group of form controls.
In summary, <fieldset>
is a helpful HTML element for structuring and organizing forms, especially when dealing with multiple related form controls. It enhances both the visual design and the accessibility of the form.