The <label> element
Examples
Defining an implicit label
<label>Click me <input type="text" /></label>
Defining an explicit label with the "for" attribute
<label for="username">Click me to focus on the input field</label> <input type="text" id="username" />
Accessibility concerns
Interactive content
Don't place interactive elements such as anchors or buttons inside a label
. Doing so makes it difficult for people to activate the form input associated with the label
.
Don't do this:
<label for="tac"> <input id="tac" type="checkbox" name="terms-and-conditions" /> I agree to the <a href="terms-and-conditions.html">Terms and Conditions</a> </label>
Prefer this:
<label for="tac"> <input id="tac" type="checkbox" name="terms-and-conditions" /> I agree to the Terms and Conditions </label> <p> <a href="terms-and-conditions.html">Read our Terms and Conditions</a> </p>
Headings
Placing heading elements within a <label>
interferes with many kinds of assistive technology, because headings are commonly used as a navigation aid. If the label's text needs to be adjusted visually, use CSS classes applied to the <label>
element instead.
If a form, or a section of a form needs a title, use the <legend>
element placed within a <fieldset>
.
Don't do this:
<label for="your-name"> <h3>Your name</h3> <input id="your-name" name="your-name" type="text" /> </label>
Prefer this:
<label class="large-label" for="your-name"> Your name <input id="your-name" name="your-name" type="text" /> </label>
Buttons
An <input>
element with a type="button"
declaration and a valid value
attribute does not need a label associated with it. Doing so may
actually interfere with how assistive technology parses the button
input. The same applies for the <button>
element.