HTML
The <legend>
tag in HTML is used to provide a caption or title for a <fieldset>
element. A <fieldset>
groups related form elements together, and the <legend>
describes the group, helping improve accessibility and understanding of the form's structure.
Example:
<form>
<fieldset>
<legend>Personal Information</legend>
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<label for="email">Email:</label>
<input type="email" id="email" name="email">
</fieldset>
<fieldset>
<legend>Account Details</legend>
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<label for="password">Password:</label>
<input type="password" id="password" name="password">
</fieldset>
</form>
Key Points:
- Semantic Use: The
<legend>
tag improves the semantic meaning of your form, making it clearer for screen readers and other assistive technologies. - Placement: It should be the first child inside the
<fieldset>
tag. - Styling: By default, it appears slightly bolder and usually positioned at the top of the fieldset. You can style it further with CSS if needed.
This is particularly useful when you have multiple sections within a form, allowing users to easily distinguish between different categories or areas.