HTML <legend> Element

Publish in HTML Tutorial el 24/05/2025 16:28

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:

Play Code


Example 2: Styled Legend

Showing how CSS can be applied to customize the legend appearance:

Play Code


Example 3: Multiple Fieldset Groups

Demonstrating how to use multiple legends in a complex form:

Play Code


Example 4: Dynamic Legend with JavaScript

Changing the legend text based on user selection:

Play Code


Example 5: Toggle Fieldset with JavaScript

Showing/hiding a fieldset and updating the legend accordingly:

Play Code


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.

También te puede interesar

HTML <style> Element
HTML <style> Element

The <style> HTML element contains style information for a document, or part of a document. ...

HTML <strong> Element
HTML <strong> Element

The <strong> element is used to indicate that its content has strong importance, seriousnes...

HTML <span> Element
HTML <span> Element

The <span> element is an inline container used to mark up a part of a text or document. Unl...

HTML <source> Element
HTML <source> Element

The <source> element is used to specify multiple media resources for media elements like &l...

HTML <small> Element
HTML <small> Element

The <small> element is used to represent side-comments and small print, typically for discl...

HTML <section> Element
HTML <section> Element

HTML <section> Element: The Complete Guide The <section> element is a semantic HTML ...