NH

Fieldset and Legend vs (radio)group and aria-labelledby

September 30, 2020

Problem

The W3 Web Accessibility Tutorials recommends grouping controls together so that it is more understanble for all users. One of the ways to semantically group controls is using <fieldset> and <legend>. The trouble is styling the tags as there’s still ongoing issues with using flex and grid with <fieldset> in chromium. Understandably the default style makes it really clear the controls (in this example radio buttons) are part of a group, but damn, it be ugly

Default style of fieldset and legend tags

<fieldset>
<legend>Output format</legend>
  <div>
    <input type="radio" name="format" id="txt" value="txt" checked>
    <label for="txt">Text file</label>
  </div>
  <div>
    <input type="radio" name="format" id="csv" value="csv">
    <label for="csv">CSV file</label>
  </div>
  […]
</fieldset>

Solution

Good thing controls can be grouped using aria, such as role="group" or role="radiogroup" instead of <fieldset> and aria-labelledby instead of legend, making it more flexible to style. Although it is still important to ensure the controls look like a group visually as well

<div role="radiogroup" aria-labelledby="radio-description" class="radio_group">
	<h4 id="radio-description">Output format</h4>
	<div>
        <input type="radio" name="format" id="txt" value="txt" checked>
        <label for="txt">Text file</label>
    </div>
    <div>
        <input type="radio" name="format" id="csv" value="csv">
        <label for="csv">CSV file</label>
    </div>
    […]
</div>
.radio_group {
	background: #FAFAFA;
	box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
	border-radius: 5px;
    padding: 16px;
}

References


Hey, I'm Nancy Huynh
I'm a self-taught front-end developer relaxing in Toronto
This is a collection of new things I'm learning