Search code examples
htmlcsschecked

not(:checked) not working if checkbox nested into element


I have the following code to hide or show the element id="my_text" depending on if the checkbox is checked not:

<style>
input[id=my_checkbox]:not(:checked) ~ #my_text  {
    display:none;
}
</style>

<div class="trigger">
    <input type="checkbox" id="my_checkbox">
</div>

<div id="my_text">
    Hide/show this sentence.
</div>

This isn't working, the element id="my_text" is always shown.

But when I remove the <div> the checkbox is nested in (or at least the closing </div> tag) like this:

<style>
input[id=my_checkbox]:not(:checked) ~ #my_text  {
    display:none;
}
</style>

<input type="checkbox" id="my_checkbox">

<div id="my_text">
    Hide/show this sentence.
</div>

it's working as expected.

Why isn't my CSS working if the checkbox is nested in an element?


Solution

  • The General sibling combinator

    The general sibling combinator (~) separates two selectors and matches the second element only if it follows the first element (though not necessarily immediately), and both are children of the same parent element.

    You need to use the HTML <label> element which represents a caption for an item in a user interface to make it work, since css doesn't have the parent selector yet

    input[id=my_checkbox]:not(:checked) ~ #my_text  {
        display:none;
    }
    <div class="trigger">
        <label for=my_checkbox>checkbox</label>
    </div>
    <input type="checkbox" id="my_checkbox">
    <div id="my_text">
        Hide/show this sentence.
    </div>