-2

I'm about to style some checkboxes for Bootstrap 3, and I absolutely cannot get my head around why in their examples they use this markup:

<label>
  <input type="checkbox"> Check me out
</label>

instead of this:

<input type="checkbox" id="a"><label for="a">Check me out</label>

I just would love to know why they went with the nested approach. I can't see any upsides. The huge huge downside is, that checked/unchecked states cannot be styled with CSS such as:

input:checked + label { }
Hugh W
  • 716
  • 2
  • 10
  • 33
Ti Hausmann
  • 926
  • 8
  • 21
  • Who are "they" and where do they use this markup? – Alohci Jul 17 '17 at 15:05
  • It is not common that the reasons for particular markup choices are documented so answers on stackoverflow are likely to be opinionated speculation. You'd be better off asking the developers of the framework directly. They have [an issues tracker](https://github.com/twbs/bootstrap/issues), and [a twitter account](https://twitter.com/getbootstrap). – Quentin Jul 17 '17 at 16:06
  • 1
    Thanks. Here are the examples: http://getbootstrap.com/css/#forms-example – Ti Hausmann Jul 18 '17 at 08:15
  • Possible duplicate of [Should I put input tags inside a label tag?](https://stackoverflow.com/questions/774054/should-i-put-input-tags-inside-a-label-tag) – Hugh W Sep 06 '18 at 11:06

1 Answers1

0

The answer is user-experience. Nesting your radio or checkbox inputs inside a <label> provides additional functionality. Consider:

<label>
    <input type="checkbox" value="">
    This is my Checkbox Option inside a Label
</label>

In the above code the checkbox is selected by clicking on either the box itself or the text within the <label>.

While in the below code the <label> text is not clickable. The only way to select the checkbox is to click directly upon the box.

<input type="checkbox" value="">
<label>This is my Checkbox Option outside a Label</label>
Robert
  • 6,881
  • 1
  • 21
  • 26
  • 3
    You can get the same effect by using a `for` attribute as per the example in the question. – Quentin Jul 17 '17 at 16:03
  • 2
    @Quentin very true! That requires additional syntax though; a unique ID to every form input and a defined `for` for every ` – Robert Jul 17 '17 at 16:08
  • but it can't be styled using CSS : https://stackoverflow.com/questions/41811551/custom-styling-for-checkbox-with-input-within-label ? – RzR Sep 11 '18 at 15:01