655

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>
bignose
  • 24,957
  • 12
  • 70
  • 100
jpsimard-nyx
  • 7,779
  • 6
  • 29
  • 47
  • 124
    One of the big pros of putting the `` inside the ` – Znarkus Sep 11 '11 at 14:56
  • 16
    While I agree that `input` does not semantically belong inside of a `label`, I noticed today that the [developers of Bootstrap disagree with me](http://getbootstrap.com/css/#forms-controls). Some elements, such as inline checkboxes, are styled differently depending on whether the `input` is inside or out. – Blazemonger Aug 21 '13 at 21:41
  • 6
    BTW this was a really bad idea to create ` – MaxZoom Sep 22 '15 at 21:01
  • 5
    @MaxZoom if you have so many different forms on your page with identical field names that you're having trouble coming up with unique IDs, you might want to reconsider your page design a little, IMHO; obviously I don't know your situation, but that just [smells bad](https://en.wikipedia.org/wiki/Code_smell) to me – Ken Bellows Apr 27 '16 at 13:25
  • 5
    @kenbellows It is a designer/business (not my) idea to put two Search forms on one page. The best user experience practices may change over time but the HTML should be flexible enough (IMHO) to cover any visible scenario. – MaxZoom Apr 28 '16 at 21:32
  • 1
    @kenbellows I do not think of this as a code smell. ASP.NET MVC's Html helpers (Html.EditFor, etc...) are able to come up with reasonable names /ids based on the datamodel (not perfect for sure). Unless you roll something like that for client side (eg, knockout), using partial views or repeating controls will immediately hit this issue. If I have something repeating, it becomes very contextual as to how to create unique ids and IMO doesn't really add any value. – MPavlak May 16 '16 at 17:11
  • 1
    One sidenote (regarding @Znarkus comment) "The label element may contain at most one button, input, keygen, meter, output, progress, select, or textarea descendant." – jave.web Aug 31 '16 at 17:58
  • @Blazemonger Semantically speaking, label acts as a control for focus, so for checkboxes&radio buttons that are selected by square area around them - it is a correct use. Though I agree there should be a special "control" element only – jave.web Aug 31 '16 at 18:02
  • The second way brings about Jsoup parsing problems. I cannot get the value of input in this label, neither with `inputElement.val()` nor `labelElement.val()`. Big issue here.... – WesternGun Jul 04 '17 at 13:09
  • 1
    @kenbellows I disagree it's a code smell. There are many perfectly valid use cases for reusing forms in a page. As a simple example, a table with in-place editing may have an instance of a single form on each row and potentially in multiple columns. Search functionality within sections of the page is another. – guioconnor Feb 09 '18 at 15:01
  • Keeping `input` inside `label` seem to cause [alignment problems](https://stackoverflow.com/questions/306252/how-to-align-checkboxes-and-their-labels-consistently-cross-browsers) – Venkata Raju Feb 18 '19 at 14:18

15 Answers15

570

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.

Liam
  • 22,818
  • 25
  • 93
  • 157
superUntitled
  • 21,375
  • 26
  • 81
  • 106
  • 14
    As answered, all are valid but in my own practice I typically settle on the first example given here by superUntitled for textboxes, textareas, and selects. But for radio buttons and checkboxes, I usually use the third example, where I want the input before the accompanying text and don't want the same kind of fixed width and/or floating that the rest of the labels and fields are using. So on any single given form, you might find me using both of these formats together. – Funka Jun 08 '11 at 00:36
  • 7
    I wonder if `` is a pass according to their criteria. – Matt Feb 01 '12 at 22:53
  • @FelipeAls not hard to code ? When nesting components in asp.net their id is prefixed with id of all their container 'ancestors'. So you can't easily guess what would be the for value. Of course you would still be able to get this value, but this is needlessly complicated vs label input/ /label construct – frenchone Jan 17 '14 at 11:46
  • 79
    Too bad that you can not nest a label inside an input tag. Would be much more semantically rational, since the label really is a property of the input, if you see it from an abstract point of view. – Alex Mar 14 '14 at 07:04
  • @frenchone The ASP.NET `Label` control has an `AssociatedControlID` property that allows you to add an appropriate "for" attribute to a label. See http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.label.associatedcontrolid(v=vs.110).aspx – Thomas Higginbotham Mar 25 '14 at 12:48
  • @Alex totally agree. would also be cool if labels were automatically prepended to inputs, forever freeing us from the ugliness of labels in forms. – r3wt Jul 06 '14 at 14:06
  • 9
    The linked WCAG document includes the following option "The control is contained within a label element that contains the label text." I don't know if that was added in the years since @Sorcy commented, but the input-in-label scenario is considered valid now. – Alex Weitzer Aug 14 '14 at 21:29
  • 2
    Oh, apparently they changed it. Hooray for sanity! – Sorcy Aug 15 '14 at 09:57
  • Third option is also less error prone. Ever seen a site where there's an input, but clicking it somehow targets a different input element that's not expected? Can be bad if it was for a check-box that's not in view. – Brett Ryan Oct 08 '14 at 10:31
  • 6
    There is an issue with the input inside label, at least in chrome, when you attach a click event handler to the label, the handler gets fired twice when the label is clicked. You can get by this with `return false;` at the end of the handler, but if you possibly have other handlers that need to execute afterwards, and stopping propagation isn't an option, this becomes an issue. – wired_in Dec 04 '14 at 21:22
  • 2
    There is a problem with wrapping `label` around `input`, that's if you want to change the label's style according to the `checked` state of the radio/checkbox, you cannot do so with pure CSS. – Tianzhen Lin Aug 16 '15 at 05:20
  • 1
    One limitation of the first and last options: they do not allow a pure CSS toggle switch (e.g. http://codepen.io/mallendeo/pen/eLIiG). For that, you need the label following the input so that you can use an adjacent sibling selector to style the on/off states of the toggle. – jbyrd Sep 04 '15 at 16:29
  • 2
    @FelipeAls & sorcy Can you please remove your comments about #3 not being a valid approach? This makes things horribly confusing; there are so many up votes for the comment that is no longer true. – MPavlak May 16 '16 at 17:16
  • @superUntitled is explain in best way and detailed. it doesn't matter, where you placed on entire page, It should be link via label 'for' attribute and input have same 'ID'. for Example, table on 1 column is having label for and 2 column is having input box. – Devang Solanki Nov 18 '16 at 12:32
  • 1
    @Matt nesting plus id does not work in Firefox v54 and IE11 and Chrome 59. – David Balažic Jul 07 '17 at 13:13
  • One thing to note is that the input must have a "name" attribute in order for clicking the label to focus it. – frodo2975 Aug 22 '17 at 18:24
  • @superUntitled another note on the third approach is that it does not work in IE6. – user966939 Oct 25 '17 at 00:42
  • @Alex: that would also make it possible to style `label` depending on eg. a checkbox is checked etc. – marlar Dec 06 '17 at 16:12
  • I down-voted this answer because it seems to say what the OP already knew: That both methods are valid. The question was about best practices: Why would a person chose one method over another. Of course, I do see that the OP voted it as the best answer, which is a mystery to me. – Syntax Junkie Mar 24 '18 at 21:00
  • @RandallStewart OP probably selected this as best because it _also_ provided usage guidance, which was the question. At the time of the choice, there were a lot fewer answers as well. Some may be better _now_ but not then. – Chindraba Mar 25 '18 at 03:43
  • @Alex On second thought, if you think about a different analogy: a piece of paper that says "FREE" on it, and then you sit a toaster on the edge of the paper because you want to indicate that the toaster is free for the taking. Labels can also be platforms / containers for what they are labeling. Perhaps inside or outside could make sense. – ADJenks Feb 05 '19 at 21:34
  • The third option (implicit labels) has accessibility issues with screen readers, because assistive technologies [do not correctly handle them](https://www.w3.org/WAI/WCAG20/Techniques/ua-notes/html#H90). – CITguy Mar 04 '19 at 17:07
  • One reason to use the `` (label after input) method would be to leverage the `:invalid` pseudo-class on all input elements to apply styles to your label, like making it red or bold or putting a warning icon next to it (e.g. `input:invalid + label { color: red }`). – Jeff Jenkins Jul 07 '19 at 22:07
  • You could wrap your label text in a span and get the same result: `` and `label input:invalid + span` – superUntitled Jul 11 '19 at 22:23
  • It can but it shouldn't. Nesting the input inside its label control is what we otherwise call a malformed or more precisely in this case - wrong nesting. – Bekim Bacaj Jul 24 '20 at 20:34
73

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.

Etienne Neveu
  • 12,254
  • 9
  • 33
  • 58
Znarkus
  • 21,120
  • 20
  • 71
  • 104
  • 4
    Including the input inside the label is the same as using HTML for layout. – Emil Sep 13 '11 at 08:08
  • 8
    I like this solution also for cases like this: `` (label is before and after the input element) – Philipp Jul 28 '14 at 11:37
  • I think the last example is - besides the for and id attributes - not really any different from having the label next to the input and both wrapped into a `div`, `li` or what not, is it!? – retrovertigo May 30 '15 at 06:59
  • 1
    @retrovertigo - functionally? No. It just reduces markup, and reduces semantic overuse of terms. We know the input `firstname` should follow the label for `firstname`, but browsers need the declaration. It's all a matter of taste and what YOU think looks best (and is easiest to debug) in your code. I prefer to use nested now, though it took a while for me to get used to it. – Xhynk Jul 28 '15 at 21:35
  • Unfortunately this breaks WCAG2.0 AA compliance around implicit labelling, but adding a `for` attribute on the label should fix it again. – James Westgate Mar 10 '16 at 12:35
  • @JamesWestgate Can you please provide a link to where it says that? From what I can tell, implicit labels are perfectly acceptable with a note that *SOME* AT do not handle it well, while many others handle it fine. – MPavlak May 16 '16 at 17:18
  • 4
    @MPavlak - a quick look and I found this guidance from w3.org. https://www.w3.org/WAI/tutorials/forms/labels/. I then checked https://www.w3.org/TR/WCAG20-TECHS/H44.html. At the bottom (it is obscure) it says that in order to claim conformance, you need to pass the test criteria, and that specifically states that you should use the for attribute. In reality when I last tested this in Apple Voiceover (10% market share screenreaders desktop, 60% market share screenreaders mobile) implicit labels didnt work, so that was another major factor. Hope that helps! – James Westgate May 17 '16 at 13:33
  • @JamesWestgate I think the bigger problem is that there are many ways to pass acceptance criteria which do not involve using explicit labels. By failing to meet acceptance H44 does not mean you are not in some other way (eg, title or aria attributes) meeting accessibility. Or am I not understanding that correctly? – MPavlak May 20 '16 at 20:30
  • @MPavlak - specifically title is a big no no in accessibility. I can link articles about that if you like, or just google it ;) Just do not use it is your best option. If you can use a label, use a label. If there is an implicit label, adding a for attribute vs adding an aria tag is going to give you a better result. But if you cant add the label (eg backend issues) then fallback to using aria attributes. – James Westgate May 23 '16 at 10:35
  • The interest of that solution is to be able to use CSS pseudo-selector :focus-within on the label to highlight it when the associated input is focused. – kalvn Apr 10 '18 at 07:44
45

Behavior difference: clicking in the space between label and input

If you click on the space between the label and the input it activates the input only if the label contains the input.

This makes sense since in this case the space is just another character of the label.

<p>Inside:</p>

<label>
  <input type="checkbox" />
  |&lt;----- Label. Click between me and the checkbox.
</label>

<p>Outside:</p>

<input type="checkbox" id="check" />
<label for="check">|&lt;----- Label. Click between me and the checkbox.</label>

Being able to click between label and box means that it is:

  • easier to click
  • less clear where things start and end

Bootstrap checkbox v3.3 examples use the input inside: http://getbootstrap.com/css/#forms Might be wise to follow them. But they changed their minds in v4.0 https://getbootstrap.com/docs/4.0/components/forms/#checkboxes-and-radios so I don't know what is wise anymore:

Checkboxes and radios use are built to support HTML-based form validation and provide concise, accessible labels. As such, our <input>s and <label>s are sibling elements as opposed to an <input> within a <label>. This is slightly more verbose as you must specify id and for attributes to relate the <input> and <label>.

UX question that discusses this point in detail: https://ux.stackexchange.com/questions/23552/should-the-space-between-the-checkbox-and-label-be-clickable

  • This isn't a spec difference. The toggle works for both cases in all compliant browsers. – hexalys Dec 26 '14 at 20:32
  • @hexalys Thanks for the report. I've updated the answer. Do you mean compliant browsers should toggle or not on both cases? If you could link to the relevant standard passage that would be awesome. – Ciro Santilli新疆棉花TRUMP BAN BAD Dec 26 '14 at 20:40
  • As long as an explicit `for` attribute is associated with an input type, it shall focus and/or toggle on modern browsers (see [compat](http://www.thecssninja.com/talks/abuse_checkboxes/#/17)). There are few browser exceptions though such as iOS that need a [hack](http://stackoverflow.com/a/6472181/1647538). – hexalys Dec 26 '14 at 21:04
  • @hexalys are we talking about the same thing: cliking *between* label and input checkbox? – Ciro Santilli新疆棉花TRUMP BAN BAD Dec 26 '14 at 21:24
  • 1
    Yes. Though I failed to notice that your example is misleading because your space isn't really a *text space*. It's a `margin` of the checkbox. The Firefox behavior on your example is peculiar and seems like a bug. A `label` will contain the spaces or padding around inline content as clickable. But given that a label's Content model is inline/[Phrasing content](https://html.spec.whatwg.org/multipage/forms.html#the-label-element) the margin of input shouldn't be clickable, unless your label is made `display: block` in which case the inside of the label `block` become clickable in all browsers. – hexalys Dec 26 '14 at 22:56
  • 1
    Note that the Bootstrap link in the answer goes to the docs for v3.3. The [docs for v4.0](https://getbootstrap.com/docs/4.0/components/forms/#checkboxes-and-radios) seem to indicate they've changed their mind: "Checkboxes and radios use are built to support HTML-based form validation and provide concise, accessible labels. As such, our s and – Michael Krebs Mar 25 '18 at 08:19
  • 2
    This behavior difference is the big one for me. When the elements are siblings, any margin on either element **reduces the clickable surface area** that'll trigger the input element. Nesting the input inside the label preserves the maximum clickable area, giving maximum accessibility even for users that struggle with precise mouse or touch movements. In Bootstrap 4, nesting **does still work** and still displays the same without needing to adjust or override any Bootstrap CSS. – Turgs Jun 20 '18 at 09:43
42

If you include the input tag in the label tag, you don't need to use the 'for' attribute.

That said, I don't like to include the input tag in my labels because I think they're separate, not containing, entities.

Terry
  • 1,068
  • 6
  • 10
  • 9
    The for requires you to use an id though, which makes structuring the layout hierarchically very hard :-( – lethalman Apr 18 '13 at 10:51
19

Personally I like to keep the label outside, like in your second example. That's why the FOR attribute is there. The reason being I'll often apply styles to the label, like a width, to get the form to look nice (shorthand below):

<style>
label {
  width: 120px;
  margin-right: 10px;
}
</style>

<label for="myinput">My Text</label>
<input type="text" id="myinput" /><br />
<label for="myinput2">My Text2</label>
<input type="text" id="myinput2" />

Makes it so I can avoid tables and all that junk in my forms.

Parrots
  • 25,268
  • 14
  • 56
  • 78
  • 3
    Shouldn't you leave presentation to CSS, instead of using `
    ` to separate the inputs?
    – Znarkus Sep 11 '11 at 14:47
  • 1
    @Znarkus - yes, normally I wrap them in OL/LIs to deal with formatting like that, this was just a quick shorthand example. – Parrots Sep 11 '11 at 15:01
  • 1
    @Parrots: That doesn't make much sense semantically, imo. And if you need to wrap them, why not just wrap them with the label? – Znarkus Sep 11 '11 at 15:06
  • @Znarkus it's an ordered list of fields you want the user to fill out, right? If you want the labels to appear to the left and be fixed-width (UX of positioning labels to the left or above the field aside), keeping the inputs outside the label avoids the need for fixed positioning. – Parrots Sep 12 '11 at 22:49
  • 1
    @Parrots With that reasoning I think everything on a page should go inside ul/li. And with `` you have all the styling options you'd (ever) need. – Znarkus Sep 13 '11 at 08:35
  • @Znarkus Ah, sure, the inclusion of the span tag will fix the width thing for you. – Parrots Sep 13 '11 at 13:47
  • 1
    Using "for" enforces you to use an id, which is bad for hierarchical layouts. – lethalman Apr 18 '13 at 10:51
16

See http://www.w3.org/TR/html401/interact/forms.html#h-17.9 for the W3 recommendations.

They say it can be done either way. They describe the two methods as explicit (using "for" with the element's id) and implicit (embedding the element in the label):

Explicit:

The for attribute associates a label with another control explicitly: the value of the for attribute must be the same as the value of the id attribute of the associated control element.

Implicit:

To associate a label with another control implicitly, the control element must be within the contents of the LABEL element. In this case, the LABEL may only contain one control element.

Alex Shesterov
  • 21,630
  • 10
  • 65
  • 88
user470514
  • 161
  • 1
  • 2
13

Both are correct, but putting the input inside the label makes it much less flexible when styling with CSS.

First, a <label> is restricted in which elements it can contain. For example, you can only put a <div> between the <input> and the label text, if the <input> is not inside the <label>.

Second, while there are workarounds to make styling easier like wrapping the inner label text with a span, some styles will be in inherited from parent elements, which can make styling more complicated.

3rd party edit

According to my understanding html 5.2 spec for label states that the labels Content model is Phrasing content. This means only tags whose content model is phrasing content <label> are allowed inside </label>.

Content model A normative description of what content must be included as children and descendants of the element.

Most elements that are categorized as phrasing content can only contain elements that are themselves categorized as phrasing content, not any flow content.

surfmuggle
  • 4,724
  • 6
  • 38
  • 68
nicholaides
  • 18,109
  • 10
  • 60
  • 81
8

A notable 'gotcha' dictates that you should never include more than one input element inside of a <label> element with an explicit "for" attribute, e.g:

<label for="child-input-1">
  <input type="radio" id="child-input-1"/>
  <span> Associate the following text with the selected radio button: </span>
  <input type="text" id="child-input-2"/>
</label>

While this may be tempting for form features in which a custom text value is secondary to a radio button or checkbox, the click-focus functionality of the label element will immediately throw focus to the element whose id is explicitly defined in its 'for' attribute, making it nearly impossible for the user to click into the contained text field to enter a value.

Personally, I try to avoid label elements with input children. It seems semantically improper for a label element to encompass more than the label itself. If you're nesting inputs in labels in order to achieve a certain aesthetic, you should be using CSS instead.

Aaron
  • 4,862
  • 1
  • 16
  • 20
  • 4
    This isn't a "gotcha". It's explicitly part of the spec; the label may contain up to 1 control in it. You're also mixing the implicit and explicit styles here -- if you put the control inside the label, you don't need `for`...and if you want to use `for`, then having the control inside the label doesn't make much sense. – cHao Nov 27 '11 at 03:49
  • True, but it would seem that this specification isn't well-understood. We ran into this issue with Drupal 6's forms API, which generated markup that created a scenario not unlike that described above. It had my colleague and I scratching our heads for a minute or two, so I thought I'd air out the issue here to avert potential confusion in the future. – Aaron Nov 30 '11 at 00:06
  • no need for "for" in label->input scenario. one input per label and it has the benefit of not having to know the name or id and you can do nice css styling to keep things encapsulated as well as having the focus occur when any other element such within is clicked. see zipstory.com/signup for example of clean way of doing this. – King Friday May 15 '12 at 01:48
  • Thank you; this answered another related question I had, namely whether it goes to have potentially more than one input inside a label. (Context: Several radio button options, one per line, each radio button entry having 1, 2, 3, or possibly more inputs of type text, with the intent of clicking on a line having the result of selecting that line's radio button, if not selected, and allowing editing of the input/inputs on that line.) This leaves the door open to having multiple labels for non-input text in the form, but it answered my question about whether what I thought of was OK. (It wasn't.) – Christos Hayward Nov 21 '13 at 20:14
7

As most people have said, both ways work indeed, but I think only the first one should. Being semantically strict, the label does not "contain" the input. In my opinion, containment (parent/child) relationship in the markup structure should reflect containment in the visual output. i.e., an element surrounding another one in the markup should be drawn around that one in the browser. According to this, the label should be the input's sibling, not it's parent. So option number two is arbitrary and confusing. Everyone that has read the Zen of Python will probably agree (Flat is better than nested, Sparse is better than dense, There should be one-- and preferably only one --obvious way to do it...).

Because of decisions like that from W3C and major browser vendors (allowing "whichever way you prefer to do it", instead of "do it the right way") is that the web is so messed up today and we developers have to deal with tangled and so diverse legacy code.

slashCoder
  • 1,149
  • 19
  • 21
5

I usually go with the first two options. I've seen a scenario when the third option was used, when radio choices where embedded in labels and the css contained something like

label input {
    vertical-align: bottom;
}

in order to ensure proper vertical alignment for the radios.

Machavity
  • 28,730
  • 25
  • 78
  • 91
Victor Ionescu
  • 1,809
  • 2
  • 21
  • 23
2

Referring to the WHATWG (Writing a form's user interface) it is not wrong to put the input field inside the label. This saves you code because the for attribute from the label is no longer needed.

Benny Neugebauer
  • 40,817
  • 21
  • 196
  • 177
2

I greatly prefer to wrap elements inside my <label> because I don't have to generate the ids.

I am a Javascript developer, and React or Angular are used to generate components that can be reused by me or others. It would be then easy to duplicate an id in the page, leading there to strange behaviours.

Nicolas Zozol
  • 6,609
  • 1
  • 46
  • 66
2

One thing you need to consider is the interaction of checkbox and radio inputs with javascript.

Using below structure:

<label>
  <input onclick="controlCheckbox()" type="checkbox" checked="checkboxState" />
  <span>Label text</span>
</label>

When user clicks on "Label text" controlCheckbox() function will be fired once.

But when input tag is clicked the controlCheckbox() function may be fired twice in some older browsers. That's because both input and label tags trigger onclick event attached to checkbox.

Then you may have some bugs in your checkboxState.

I've run into this issue lately on IE11. I'm not sure if modern browsers have troubles with this structure.

Mariusz
  • 73
  • 1
  • 7
0

There are several advantages of nesting the inputs into a label, especially with radio/checkbox fields,

.unchecked, .checked{display:none;}
  label input:not(:checked) ~ .unchecked{display:inline;}
  label input:checked ~ .checked{display:inline;}
<label>
  <input type="checkbox" value="something" name="my_checkbox"/>
  <span class="unchecked">Not Checked</span>
  <span class="checked">Is Checked</span>
</label>

As you can see from the demo, nesting the input field first followed by other elements allows,

  • The text to be clicked to activate the field
  • The elements following the input field to be dynamically styled according to the status of the field.

In addition, HTML std allows multiple labels to be associated with an input field, however this will confuse screen readers and one way to get round this is to nest the input field and other elements within a single label element.

Aurovrata
  • 1,264
  • 17
  • 32
  • You can still do the same with unnested labels : https://jsfiddle.net/n4zc95s1/ And having a single label meaning 2 different thing like this proposal might be problematic to get an accessible form. For the sake of WCAG, I'd go split with this one. – jpsimard-nyx Apr 12 '21 at 02:45
  • true, but I still find one label for one input field is much cleaner to work with. Nesting the input in the label also allows for pseudo elements to be inserted and doing more complex UIs such as [checkbox tree views](https://codepen.io/aurovrata/pen/VwPXreX). – Aurovrata Apr 13 '21 at 09:15
-1

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 omit for and id: <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

ThisClark
  • 12,145
  • 9
  • 61
  • 89