当:nth-​​child为:选中时,选择相应的:nth-​​child,无限子女

时间:2017-10-20 21:53:53

标签: css css-selectors

我们说我的布局是这样的:

<input id="radio1" name="radio" type="radio" hidden>
<input id="radio2" name="radio" type="radio" hidden>
<input id="radio3" name="radio" type="radio" hidden>

<section>
  <label for="radio1">One</label>
  <label for="radio2">Two</label>
  <label for="radio3">Three</label>
</section>

仅在CSS中,我希望能够检查单选按钮并选择相应的标签。如果我知道孩子的数量,我可以轻松地做到这一点:

:checked:nth-of-type(1) ~ section label:nth-of-type(1),
:checked:nth-of-type(2) ~ section label:nth-of-type(2),
:checked:nth-of-type(3) ~ section label:nth-of-type(3){
  color: blue;
  font-weight: bold;
}

Example Pen for the above example ^

但如果有n个孩子,该怎么办?有人会认为你可以简单地使用:

:checked:nth-of-type(n) ~ section label:nth-of-type(n)

但这不起作用。

是否可以在不使用JS或更改HTML结构的情况下在单个选择器中选择相应的子项?

1 个答案:

答案 0 :(得分:1)

  

是否可以在单个选择器中选择相应的子项   不使用JS或更改HTML结构?

没有。使用当前的CSS伪类范围是不可能的。

但是,在假设的情况下,如果您可以更改HTML结构......

...然后你可以利用下一个兄弟选择器+

工作示例:

:checked + label {
color: red;
font-weight: bold;
}

label, input {
position: relative;
display: inline-block;
width: 48px;
text-align: center;
cursor: pointer;
}

input {
z-index: 6;
opacity: 0;
}

label {
margin-left: -48px;
}
<section>
<input name="radio-set" type="radio" />
<label>One</label>
<input name="radio-set" type="radio" />
<label>Two</label>
<input name="radio-set" type="radio" />
<label>Three</label>
<input name="radio-set" type="radio" />
<label>Four</label>
<input name="radio-set" type="radio" />
<label>Five</label>
<input name="radio-set" type="radio" />
<label>Six</label>
</section>

相关问题