I've been reading the w3.org HTML5 form spec, and was surprised to see the following HTML:
<p><label>Customer name: <input name="custname"></label></p>
<p><label>Telephone: <input type=tel name="custtel"></label></p>
<p><label>E-mail address: <input type=email name="custemail"></label></p>
Semantically, this confuses me. Wouldn't a <label>
make more sense as a sibling to an <input>
, rather than as its parent?
In the wild, I'm more used to seeing the following configuration:
<p>
<label for="customer_name">Customer name:</label>
<input id="customer_name" name="customer[name]">
</p>
I know that a large majority of markup out there is malformed, but I'm interested to hear others' thoughts on what the proper convention should be.
I stand corrected, but it seems every markup generator and form helper I've used essentially violates the W3's suggestions - even those that claim HTML5 support, making use of client-side validations and the like.
Thoughts?
Both forms are valid, per the spec:
The for attribute may be specified to indicate a form control with which the caption is to be associated. If the attribute is specified, the attribute's value must be the ID of a labelable form-associated element in the same Document as the label element. If the attribute is specified and there is an element in the Document whose ID is equal to the value of the for attribute, and the first such element is a labelable form-associated element, then that element is the label element's labeled control.
If the for attribute is not specified, but the label element has a labelable form-associated element descendant, then the first such descendant in tree order is the label element's labeled control.
You can either use nesting, if that makes sense for your markup, or use the for attribute if you're unable to use implicit nesting. Neither is more or less correct than the other. I presume most people favor using the for attribute since that gives the author the most flexibility by allowing the two elements to be decoupled from each other.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With