Is there a best practice concerning the nesting of label
and input
HTML elements?
classic way:
The primary advantage of placing input
inside of label
is typing efficiency for humans and byte storage for computers.
@Znarkus said in his comment to the OP,
One of the big pros of putting the
<input />
inside the<label>
, is that you can omitfor
andid
:<label>My text <input /></label>
in your example. So much nicer!
Note: In @Znarknus code, another efficiency was included not explicitly stated in the comment. type="text"
can also be omitted and input
will render a text box by default.
A side by side comparison of keystrokes and bytes[1].
31 keystrokes, 31 bytes
<label>My Text<input /></label>
58 keystrokes, 58 bytes
<label for="myinput">My Text</label><input id="myinput" />
Otherwise, the snippets are visually equal and they offer the same level of user accessibility. A user can click or tap the label to place the cursor in the text box.
[1] Text files (.txt) created in Notepad on Windows, bytes from Windows File Explorer properties
From w3:
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.