将鼠标悬停在相关复选框上时,如何激活标签的CSS样式?

mat*_*att 11 html css css-selectors

每次我将鼠标悬停在复选框的标签上都会变为黄色:

标记

<input type="checkbox" value="hello" id="hello" name="deletefiles[]"/>
<label for="hello">hello</label>
Run Code Online (Sandbox Code Playgroud)

CSS

label:hover, label:active {
   background:yellow;
}
Run Code Online (Sandbox Code Playgroud)

当我将鼠标悬停在相关复选框上时,我希望标签突出显示.如果我将鼠标悬停在复选框上,是否有办法使用CSS触发相同的悬停规则?或者我必须使用JavaScript ...?

SLa*_*aks 17

你可以使用CSS兄弟选择器,如下所示:

label:hover, label:active, input:hover+label, input:active+label {
    background:yellow;
}
Run Code Online (Sandbox Code Playgroud)

请注意,这在IE6中不起作用.

  • 我停止支持ie6 5年前!:) (5认同)
  • @mathiregister:实际上,[您可以使用 :checked 伪类](http://www.w3.org/Style/CSS/Test/CSS3/Selectors/current/html/full/flat/css3-modsel-25 .html) 就像您已经在使用 :hover 和 :active... 不同之处在于它不适用于任何当前发布的 IE 版本... (2认同)

Sho*_*og9 6

只需将复选框放在标签内:

<label for="hello">
  <input type="checkbox" value="hello" id="hello" name="deletefiles[]"/>
  hello
</label>
Run Code Online (Sandbox Code Playgroud)

现在,当您将鼠标悬停在复选框上时,您也会将鼠标悬停在标签上,现有规则就足以突出显示它.

  • @ WalterJ89:确实是...实际上,当相关输入嵌套在其中时,您可以跳过标签上的`for`属性! (2认同)