New HTML rule: disallow wrapping of legend in a div

I often see front-end developers wrap a legend element in a div in order to have more styling options. Unfortunately, that makes the legend element useless.

Rule: the legend element must always be the first child element in a fieldset element.

Why?

  • When this condition is fulfilled, screen readers will read the legend when the first form field in the fieldset receives keyboard focus. If any other element is wrapped around the legend element (usually a div, but p and other element must also be excluded), this will not work.
  • The HTML specification requires that the legend element must always be the first child element in a fieldset element. The W3C Validator reports a validation error when the legend element is not the first child element in a fieldset element, but most developers don’t seem to use the W3C Validator.

Snippet of non-compliant code:

<fieldset>
  <div class="...">
    <legend>Gender</legend>
  </div>
  <!-- Form elements go here.  --> 
</fieldset>

Snippet of compliant code:

<fieldset>
  <legend>Gender</legend>
  <!-- Form elements go here; div elements are fine here. --> 
</fieldset>

Potential exception

Potentially, an exception could be made if the fieldset has an aria-labelledby attribute that references the ID of the legend element, but I have never seen this in the wild:

<fieldset aria-labelledby="legend-ID">
  <div class="...">
    <legend id="legend-ID">Gender</legend>
  </div>
  <!-- Form elements go here.  --> 
</fieldset>

References:

Note that the legend element is optional, but a fieldset without a legend element has no accessibility benefits and is just a div with a fancy name.

Type: Bug (i.e. in the HTML code or DOM).