
Gabriel F. answered 11/05/19
Tutor
5.0
(85)
Full Stack Software Developer and Mentor
Hi there. Nesting an input inside a label is an alternative way to associate them (instead of using "id" in the input and "for" in the label). Either way works fine. This is what the MOZ docs say:
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. This means that, for example, a screenreader will read out the label when the user is focused on the form input, making it easier for an assistive technology user to understand what data should be entered.
You can click the associated label to focus/activate the input, as well as the input itself. This increased hit area provides an advantage to anyone trying to activate the input, including those using a touch-screen device.
To associate the<label>
with an<input>
element, you need to give the<input>
anid
attribute. The<label>
then needs afor
attribute whose value is the same as the input'sid
.
Alternatively, you can nest the<input>
directly inside the<label>
, in which case thefor
andid
attributes are not needed because the association is implicit.
I hope this helps.