The <legend> element is used to provide a caption or title for a <fieldset> element, which groups related form controls together. It helps improve accessibility and usability by giving context to the grouped form elements.
Basic Syntax
Here's how the basic structure looks:
Key Features
- Must be the first child of a <fieldset> element
- Improves form accessibility for screen readers
- Helps visually group related form controls
- Can be styled with CSS like any other text element
Examples
Example 1: Basic Form Grouping
A simple contact information form section:
Example 2: Styled Legend
Showing how CSS can be applied to customize the legend appearance:
Example 3: Multiple Fieldset Groups
Demonstrating how to use multiple legends in a complex form:
Example 4: Dynamic Legend with JavaScript
Changing the legend text based on user selection:
Example 5: Toggle Fieldset with JavaScript
Showing/hiding a fieldset and updating the legend accordingly:
Tips and Tricks
- Accessibility: Always use <legend> with <fieldset> to help screen readers understand form structure.
- Styling: You can position the legend text anywhere on the fieldset border using CSS positioning.
- Responsive Design: Keep legend text concise as it may not wrap well on small screens.
- Visual Hierarchy: Use larger or bold text for legends to clearly distinguish different form sections.
- Dynamic Content: As shown in examples, you can modify legends with JavaScript to provide interactive feedback.