HTML & CSS Tip of the Week

The fieldset and legend elements

Published on


If you make websites—and I have to assume you at least dabble in development if you’re reading this—changes are you’ve created a <form> or two.

One thing not enough people use within their forms are <fieldset> elements.

A <fieldset> gives us a way to group elements in a form, which can be useful if you have radio or select inputs that are all part of the same group, like this:

<form>
  <fieldset>
    <legend>Pick your favorite fruit</legend>
    <input type="radio" id="apple" name="fruits" value="A" />
    <label for="apple">Apple</label>
    <input type="radio" id="orange" name="fruits" value="O" />
    <label for="orange">Orange</label>
    <input type="radio" id="mango" name="fruits" value="M" />
    <label for="mango">Mango</label>
  </fieldset>
</form>

This allows us to group those element, and the <legend> is used to create a caption for that grouping.

Disabling the entire fieldset

Sometimes, you may want to disable parts of your form.

Rather than disabling every input, you can use the disabled attribute on the fieldset, and it will disable the entire group.

You can connect a fieldset to a form

You can use the form attribute to connect a fieldset to a form, without having to have the fieldset nested inside of it.

This works by connecting to it with an id, like so:

<fieldset form="user-info">
  <legend>What is your name?</legend>
  <label>First name: <input type="text"></label>
  <label>Last name: </input type="text"></label>
</fieldset>

<!-- other content -->

<form id="user-info">
  <!-- other form content -->
</form>

Dive deeper

Proper form labeling is really important, and the <fieldset> and <legend> elements can do a lot to help do this properly.

If you’d like to dive deeper into their importance, and other ways that we can use them, I’d encourage you to check out Fieldsets, Legends and Screen Readers again.