Definition
The <legend>
HTML element is used to provide a caption or title for a <fieldset>
element, which is a grouping container for related form controls. The <legend>
element helps to provide a descriptive title or explanation for the purpose of the form controls within the fieldset.
Here’s an example of how to use the <legend>
element:
<fieldset>
<legend>Personal Information</legend>
<label for="name">Name:</label>
<input type="text" id="name" name="name" />
<!-- Additional form controls -->
</fieldset>
In this example, the <fieldset>
element creates a grouping container for a set of related form controls, such as input fields. The <legend>
element is used to provide a title “Personal Information” that describes the purpose or context of the form controls within the fieldset.
The <legend>
element is typically placed as the first child element inside the <fieldset>
element. It can contain text, images, or other HTML elements to further enhance the visual representation of the fieldset’s purpose.
Using the <legend>
element has several benefits:
- It provides a visual and semantic indication of the grouping of related form controls.
- It improves accessibility by associating the descriptive title with the form controls within the fieldset.
- It helps users understand the purpose or context of the form controls, especially in longer or complex forms.
It’s worth noting that the <legend>
element should be used within a <fieldset>
element and not on its own.