I've read that it's an accessibility best practice to always include a <label>
element along with an <input type="email">
element, but what if I don't have a label
element to include with my <input>
element?
I mean, currently, I'm designing a site that doesn't really have any text to put into a <label>
element (so I'm not creating one at all) but I don't really know what to do since my HTML is generating an accessibility error when I run it through a web accessibility checker.
Do have to make up some text to throw into a label
element to include it just to make my HTML accessible? Or is there some other way to make a lone <input type="email">
element accessible?
The label is there to identify the input. It doesn't have to be a clever name it can literally just say "email" or "email address".
There are several reasons to have a label:-
For your use case it is as simple as
<label for="emailAddress">Email</label>
<input id="emailAddress" />
Or
<label>
Email
<input/>
</label>
You could use WAI-ARIA (aria-label
for example) to add a label to an input. I would caution you against this though as support is not 100%.
Instead you could visually hide the label using CSS as that would work in all browsers back to IE6 (and even on text only browsers).
However this is also not recommended due to reasons 2 and 3 above. I have included it for completeness (and for use in search boxes where it is acceptable to not have a visible label).
For clarity, use a visible label, the benefits are worth it from accessibility and clarity perspectives.
.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 */
}
<label for="emailAddress" class="visually-hidden">Email</label>
<input id="emailAddress" placeholder="email address"/>
The placeholder text should be used for either example input or an explanation of what input is expected.
Do not use placeholders as a replacement for a label. There are various accessibility issues with this approach.
The example of how to hide a label should only be used in exceptional circumstances (the two I can think of are the site search input and possibly an email signup form that only requires an email address, even then it depends on other factors and a label would be better).