LCJ
LCJ

Reputation: 22652

Label associated with checkbox does not work when checkbox moved inside label

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>

Upvotes: 0

Views: 2700

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195992

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

Upvotes: 2

Related Questions