Search code examples
csshtmlinputwindows-store-apps

Proper Label / Input format benefits


I'm knocking dust off my html5/css3 and ran into something that made me wonder. For consideration here's two examples from competing documentation.

Is there a benefit to maintainability / design etc between these two ways of forming an input/label group, most specifically within a Windows Store App in HTML5? Please let me know if this can't be answered succinctly and may be only argued by opinions so I can del the question if so.

So from MS Docs;

<label class="a-label-class">
   <input id="option1" type="checkbox" class="a-input-class" />
   Option 1
</label>

From other docs;

<div>
   <input id="option1" class="a-input-class" name="option1" type="checkbox"/>
   <label for="option1" class="a-label-class">Option 1</label>
</div>

The first example is a little less markup. Except they appear to accomplish the same thing. However the second example utilizes for and would appear to give a little more design option using the div container.

So my question would be, is one way technically better practice for a specific reason? What are the benefits of the better approach if any? Thanks!


Solution

  • Both the approach are admitted and pratically equivalent for semantic role. The first hierarchical manner is consistent with the organization of the elements of the second DOM is more expressive and concise. Anyway if useful this below is from one of most authoritative sources

    From the HTML Living Standard — Last Updated 20 Jul

    The label element represents a caption in a user interface. The caption can be associated with a specific form control, known as the label element's labeled control, either using the for attribute, or by putting the form control inside the label element itself.

    Except where otherwise specified by the following rules, a label element has no labeled control.

    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 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 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 element descendant, then the first such descendant in tree order is the label element's labeled control.