W3docs

HTML <legend> Tag

The <legend> tag sets the caption for the group of form elements defined by the <field> tag. Description, attributes and using examples.

The <legend> tag defines the caption for a group of form elements wrapped in a <fieldset> tag. In the browser, the fieldset is visually framed, and the legend caption is rendered inside that frame. It should generally be the first child element of the <fieldset> . Grouping related form controls with <fieldset> and <legend> captions improves accessibility and usability for complex forms.

Syntax

The <legend> tag comes in pairs. The content is written between the opening <legend> and closing </legend> tags.

Example of the HTML <legend> tag:

HTML <legend> Tag

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <form>
      <fieldset>
        <legend>Personal data:</legend>
        Name:
        <input type="text" />
        <br>
        <br> E-mail:
        <input type="email" />
        <br>
        <br> Date of birth:
        <input type="number" />
        <br>
        <br> Place of birth:
        <input type="text" />
      </fieldset>
    </form>
  </body>
</html>

Result

legend tag example

Example of the HTML <legend> tag with CSS:

Example of the <legend> tag with CSS properties:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      form {
        width: 55%;
      }
      fieldset {
        padding: 25px;
      }
      label {
        display: inline-block;
        width: 95px;
        text-align: right;
      }
      legend {
        display: block;
        padding: 15px;
        margin-bottom: 10px;
        background-color: #cccccc;
        color: #777777;
      }
    </style>
  </head>
  <body>
    <form>
      <fieldset>
        <legend>Personal data:</legend>
        <label>Name:</label>
        <input type="text" />
        <br>
        <br>
        <label>E-mail:</label>
        <input type="email" />
        <br>
        <br>
        <label>Date of birth:</label>
        <input type="number" />
        <br>
        <br>
        <label>Place of birth:</label>
        <input type="text" />
      </fieldset>
    </form>
  </body>
</html>

Attributes

AttributeValueDescription
alignleft right center justifyDefines the alignment of the caption. Deprecated in HTML5; use CSS text-align or padding instead.

The <legend> tag supports the Global Attributes and the Event Attributes.

How to style an HTML <legend> Tag

You can style the <legend> element using standard CSS properties such as padding, margin, background-color, and font-weight, as demonstrated in the previous example.

Practice

Practice

What is the main function of the HTML <legend> tag?