Fieldset and Legend Elements (Live Playground)
In this tutorial, we will discuss the fieldset and legend elements in HTML forms. The fieldset element is used to group related form controls, while the legend element provides a caption for the group.
Creating a Fieldset
To create a fieldset, simply use the <fieldset> tag and wrap it around the related form controls.
<form>
<fieldset>
<label for="name">Name:</label>
<input type="text" id="name" name="name" />
</fieldset>
</form>
In this example, we have created a fieldset containing a single form control for entering the user's name.
Adding a Legend
To add a legend to a fieldset, simply use the <legend> tag within the fieldset and provide the desired caption text.
<form>
<fieldset>
<legend>Personal Information</legend>
<label for="name">Name:</label>
<input type="text" id="name" name="name" />
</fieldset>
</form>
In this example, we have added a legend to the fieldset, providing a caption of "Personal Information" for the group of form controls.
Grouping Multiple Form Controls
A fieldset can be used to group multiple form controls, making it easier for users to understand the relationship between them.
<form>
<fieldset>
<legend>Contact Information</legend>
<label for="email">Email:</label>
<input type="email" id="email" name="email" />
<label for="phone">Phone:</label>
<input type="tel" id="phone" name="phone" />
</fieldset>
</form>
In this example, we have grouped two form controls (email and phone) within a single fieldset, with a legend caption of "Contact Information".
Conclusion
In this tutorial, we have explored the fieldset and legend elements in HTML forms. By understanding how to create a fieldset and add a legend, you can group related form controls and provide clear captions, improving the usability of your forms.