I am creating a custom checkbox and want clicking the label text to also toggle the state and show or not show a text depending of the state of the checkbox just using CSS. I wrote this html:
input[type="checkbox"] {
display: none;
}
input[type="checkbox"] + .label-text:before{
content: "+";
width: 1em;
height: 1em;
display: inline-block;
margin-right: 5px;
}
input[type="checkbox"]:checked + .label-text:before{
content: "-";
}
label input[type="checkbox"]:checked ~ .elements .is_not_checked{
display: none;
}
label input[type="checkbox"]:not(:checked) ~ .elements .is_checked{
display: none;
}
<label>
<input type="checkbox" name="check"> <span class="label-text">Item Two</span>
<div class="elements">
<div class="is_checked">
Checkbox is checked
</div>
<div class="is_not_checked">
Checkbox is not checked
</div>
</label>
This works. But I am not happy with the checkbox changing state when I click on the element text. However, when I move the elements out of the label I can no longer access the checkbox state. I tried:
(label > input[type="checkbox"]:checked) ~ .elements .is_not_checked{
display: none;
}
But this did not even hide the text. How can I access the state of a checkbox hidden in another element (label in this case) just using CSS?