Using the HTML `<legend>` Element to Label `
` Groups in Forms: Enhancing Clarity and Accessibility

Learn how to use the HTML `<legend>` element to create clear and descriptive labels for groups of form elements within `

` containers. This tutorial explains its proper placement, demonstrates its use in improving form organization and accessibility, and shows how to customize its appearance using CSS.



Using the HTML `<legend>` Element to Label `
` Groups

Understanding the `<legend>` Element

The HTML `<legend>` element defines a caption for a `

` element. A `
` is a container for grouping related form elements, improving the visual organization and structure of web forms. The `<legend>` element provides a descriptive label for this group, enhancing usability and making it clear to the user what the group of form elements represents.

Using the `<legend>` Element

The `<legend>` element must be the first child element of the `

` element. It should provide a concise label for the contained form elements. For example:

Example: Basic `<legend>` Usage

<fieldset>
  <legend>Personalia</legend>
  <input type="text" name="fname">
  <input type="text" name="lname">
</fieldset>

Styling the `<legend>` Element with CSS

You can customize the appearance of the `<legend>` element using CSS. For example, you can change its position and alignment:

Example: Styling `<legend>` with CSS

legend {
  float: right; /* Float to the right */
  font-weight: bold;
  margin-right: 10px;
}

Browser Support and Default Styles

The `<legend>` element is widely supported by modern browsers. Most browsers render the legend text in bold and display it as a caption for the fieldset. The default styling generally includes displaying it as a block-level element.

Browser Support
Chrome Yes
Edge Yes
Firefox Yes
Opera Yes
Safari Yes
Default CSS for `<legend>`

legend {
  display: block;
  padding-left: 2px;
  padding-right: 2px;
  border: none;
}