What is Legend in HTML: Definition and Usage Explained
<legend> tag in HTML defines a caption for the <fieldset> element, grouping related form controls. It helps users understand the purpose of grouped inputs and improves accessibility by providing a clear label for the group.How It Works
The <legend> tag works like a title or label for a group of related form elements wrapped inside a <fieldset>. Imagine you have a box containing several questions about your contact details. The <legend> acts like the box's label, telling users what the questions inside are about.
This grouping helps users and screen readers understand the form better. The <legend> text usually appears at the top border of the <fieldset>, visually connecting the label with the grouped inputs. This makes forms easier to scan and fill out, especially for people using assistive technology.
Example
<fieldset> and a <legend> describing it.<form>
<fieldset>
<legend>Personal 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">
</fieldset>
</form>When to Use
Use the <legend> tag whenever you group related form controls inside a <fieldset>. This is especially helpful for longer forms with multiple sections, like billing details, shipping address, or preferences.
It improves clarity for all users and is essential for accessibility, as screen readers announce the <legend> to describe the group. This helps users understand the context of the inputs they are filling out.
Key Points
- The
<legend>tag labels a group of form elements inside a<fieldset>. - It visually appears as a caption on the fieldset's border.
- It improves form accessibility and user understanding.
- Always use
<legend>with<fieldset>for grouped inputs.