Is there a best practice concerning the nesting of label
and input
HTML elements?
classic way:
<label for="myinput">My Text</label>
<input type="text" id="myinput" />
or
<label for="myinput">My Text
<input type="text" id="myinput" />
</label>
There are two ways to pair a label and an input. One is by wrapping the input in a label (implicit), and the other is by adding a for attribute to the label and an id to the input (explicit). Think of an implicit label as hugging an input, and an explicit label as standing next to an input and holding its hand.
When using input elements of “type” checkbox and radio the label element should always be placed after the <input> element. Label elements should be associate with the following form elements: Input type = "text"
Associating a <label> with an <input> element offers some major advantages: The label text is not only visually associated with its corresponding text input; it is programmatically associated with it too.
Div is a block element, so cannot go inside a label which will only accept Phrasing content. You may use <span> instead as that is an in-line element. SamA74: Div is a block element, so cannot go inside a label which will only accept Phrasing content.
From the W3's HTML4 specification:
The label itself may be positioned before, after or around the associated control.
<label for="lastname">Last Name</label>
<input type="text" id="lastname" />
or
<input type="text" id="lastname" />
<label for="lastname">Last Name</label>
or
<label>
<input type="text" name="lastname" />
Last Name
</label>
Note that the third technique cannot be used when a table is being used for layout, with the label in one cell and its associated form field in another cell.
Either one is valid. I like to use either the first or second example, as it gives you more style control.
I prefer
<label>
Firstname
<input name="firstname" />
</label>
<label>
Lastname
<input name="lastname" />
</label>
over
<label for="firstname">Firstname</label>
<input name="firstname" id="firstname" />
<label for="lastname">Lastname</label>
<input name="lastname" id="lastname" />
Mainly because it makes the HTML more readable. And I actually think my first example is easier to style with CSS, as CSS works very well with nested elements.
But it's a matter of taste I suppose.
If you need more styling options, add a span tag.
<label>
<span>Firstname</span>
<input name="firstname" />
</label>
<label>
<span>Lastname</span>
<input name="lastname" />
</label>
Code still looks better in my opinion.
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