htmlaccessibility

Empty form label: A form label is present, but does not contain any content


I get the error in the title when using the Wave Accessibility tool. My HTML is below (I use it to toggle dark-light mode with JS).

<span class="theme-switch-wrapper">
       <label class="theme-switch" for="checkbox">
         <input type="checkbox" id="checkbox" />
         <span class="slider round"></span>
       </label>
     </span>

How do I solve this?


Solution

  • So your label needs some text within it that can be used as the text for assistive technology.

    At the moment you have HTML nodes but no text content.

    One way to solve this is with visually hidden text, which assistive technology can access but is not visible on the screen visually.

    Example

    In the below example I have added an extra span containing the text for your label. I have then hidden it visually using the visually-hidden class.

    .visually-hidden { 
        border: 0;
        padding: 0;
        margin: 0;
        position: absolute !important;
        height: 1px; 
        width: 1px;
        overflow: hidden;
        clip: rect(1px 1px 1px 1px); /* IE6, IE7 - a 0 height clip, off to the bottom right of the visible 1px box */
        clip: rect(1px, 1px, 1px, 1px); /*maybe deprecated but we need to support legacy browsers */
        clip-path: inset(50%); /*modern browsers, clip-path works inwards from each corner*/
        white-space: nowrap; /* added line to stop words getting smushed together (as they go onto seperate lines and some screen readers do not understand line feeds as a space */
    }
    <span class="theme-switch-wrapper">
           <label class="theme-switch" for="checkbox">
             <input type="checkbox" id="checkbox" />
             <span class="slider round"></span>
             <span class="visually-hidden">Label for the input</span>
           </label>
         </span>

    Final note

    It isn't just people using assistive tech you need to consider. Visible labels help everybody, especially those with cognitive disabilities or accuracy issues (you can click a label and it will focus the input it is associated with).

    I would suggest a slight redesign so that the label text is visible for everyone, the solution offered above is if you are constrained and cannot (not "don't want to"!) make such an adjustment to the design.