0

MDN - Attributes says:

A <label> can be associated with a control either by placing the control element inside the element, or by using the for attribute.

I was checking a demo for Animated Checkbox with CSS3 Powered Animation. I tired to make it as label with input element inside it, based on Possible to associate label with checkbox without using "for=id"?.

When I made the change, the checkbox is not working. Why is it not working after this change and how to fix this?

Working: https://codepen.io/anon/pen/LLPQoy

Not Working: https://codepen.io/anon/pen/qjWodj

Note: I cannot use "For" attribute in label since the input elements will be dynamically added in my actual HTML page.

HTML

<div class="myDiv" style="padding:20px 0 20px 20px;">
<input type="checkbox" id="cbtest" />
<label for="cbtest" class="check-box"></label> 
</div>
LCJ
  • 22,196
  • 67
  • 260
  • 418
  • 1
    your css rules are not updated in the not working. Label is the parent of .checkbox. But you are targeting like this input[type=checkbox]:checked + .check-box – karthick Jun 01 '17 at 23:44

1 Answers1

2

The checkbox works just fine, as you can see if you make it visible (it currently has display:none).

The problem is that your CSS expects it to be outside so it can style the .check-box element when using input[type=checkbox]:checked + .check-box.

To fix this you should add another element after the checkbox and add the check-box class to that instead of the label.

<label>
  <input type="checkbox" />
  <span class="check-box">
</label> 

Updated codepen at https://codepen.io/anon/pen/qjWopx

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
  • Interesting. It works. I am trying to understand the logic of adding a span to fix this. Yes, I see that it meets the CSS expectation now. What I am not able to understand is how the `for` attribute was meeting the same expectation. – LCJ Jun 01 '17 at 23:53
  • 1
    @Lijo it wasn't the `for`. In the css the `input[type=checkbox]:checked + .check-box` means that `.check-box` must be the next element after a `:checked` input, and that is how your html was in that example (*the `label` with the `.check-box` class was the next element of the input*). In the updated code we just fixed that mismatch by adding another element to be styled instead of the label. – Gabriele Petrioli Jun 01 '17 at 23:56