I see this pattern in documentation:
<input type="checkbox" id="foo" /><label for="foo">Foo!</label>
But the problem is that it leaves a dead zone between the checkbox and its label where you can click on the label and you can click on the box but there’s a little gap between the two where clicks don’t do anything and it’s kind of annoying.
Obviously this gets worse if there’s any whitespace between the input and label tags.
To fix the problem I tried this:
<label for="foo"><input type="checkbox" id="foo" />Foo!</label>
This "works for me" in that it eliminates that dead spot between box and text and is much easier to interact with. But is it legal and idiomatic HTML?
5
Answers
But the problem is that it leaves a dead zone between the checkbox and its label where you can click on the label and you can click on the box but there’s a little gap between the two where clicks don’t do anything and it’s kind of annoying.
Obviously this gets worse if there’s any whitespace between the input and label tags.
To fix the problem I tried this:
In fact, I have seen my teammates do that many times before, and it works well. But in my opinion, you can remove the gap by styling the input and label using CSS instead. Try wrap the input and label with a form-group div, display it as a flexbox, set the gap to 0, and add spacing between the input and label using padding instead of margin
(Here the code I copied from the documentation link above, added a class name
form-group
)Yes, the second one is valid and may have been used directly with no problem.
This way is more often used for labels. It is preferred for its ability to keep together both the label and the input elements, sometimes even providing an impression of organization within the code. Example:
Both are legal and functional, but the second one tends to be the go-to for many developers!
According to HTML Standard, the answer is yes and yes.
Also, you might not need to provide the
for
attribute of thelabel
if the labeled element (theinput
) is the child of thatlabel
element.The link I provided presents a lot more examples and information that you might be interested in: https://html.spec.whatwg.org/multipage/forms.html#the-label-element
Yes, this is valid.
and also by this way you don’t need to use an
id
attribute.example: