DEV Community

Cover image for A11y tips: use fieldset and legend to add context
Carlos Espada
Carlos Espada

Posted on

A11y tips: use fieldset and legend to add context

Use <fieldset> to group related elements on a form, such as radio buttons, checkboxes, or even text fields, such as a postal address. The screen reader will announce that the item belongs to a group when users focus on it.

If you also use <legend> to provide a title to the <fieldset>, that title will be announced__ along with the group membership, thus giving them even more context about the information they are about to fill in.

  <legend>Choose your favorite monster</legend>
  <input type="radio" id="kraken" name="monster" />
  <label for="kraken">Kraken</label>
  <input type="radio" id="sasquatch" name="monster" />
  <label for="sasquatch">Sasquatch</label>
  <input type="radio" id="mothman" name="monster" />
  <label for="mothman">Mothman</label>
Enter fullscreen mode Exit fullscreen mode

For example, if we have two different addresses in a checkout process and we add something like this, the user will be able to know perfectly when entering each field if what they are filling in is the shipping address or the billing address, since the label each one is the same:

  <legend>Shipping address</legend>
  <label for="shipping-street">Street</label>
  <input type="text" name="shipping-street" id="shipping-street" />
  <label for="shipping-postal-code">Postal code</label>
  <input type="text" name="shipping-postal-code" id="shipping-postal-code" />
  <label for="shipping-city">City</label>
  <input type="text" name="shipping-city" id="shipping-city" />
  <legend>Billing address</legend>
  <label for="billing-street">Street</label>
  <input type="text" name="billing-street" id="billing-street" />
  <label for="billing-postal-code">Postal code</label>
  <input type="text" name="billing-postal-code" id="billing-postal-code" />
  <label for="billing-city">City</label>
  <input type="text" name="billing-city" id="billing-city" />
Enter fullscreen mode Exit fullscreen mode

It's an extra way of providing help to these users, like we see in the previous post about messages binded using aria-describedby.

Top comments (0)