如果复选框嵌套到元素中,则 not(:checked) 不起作用

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

我有以下代码来隐藏或显示元素 id="my_text" 取决于是否选中复选框:

<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>

这不起作用,元素 id="my_text" 始终显示。

但是当我删除 <div> 时,复选框嵌套在(或至少是关闭的 </div> 标记)中,如下所示:

<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>

它按预期工作。

如果复选框嵌套在元素中,为什么我的 CSS 不起作用?

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.

您还需要使用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

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>