CSS一般同级和nth-of-type选择器-奇怪的行为?

蒂莫西·费希尔

请考虑以下代码段:

.test input.one ~ div:nth-of-type(2) {
  background-color: red;
}

.test input.two ~ div:nth-of-type(2) {
  background-color: blue;
}
<form class="test">
  <input class="one" />
  <div></div>
  <input class="two" />
  <div style="height: 50px;"></div>
  <div style="height: 50px;"></div>
</form>

我希望发生的是第一个<div style="height: 50px;"></div>是红色,第二个是蓝色。相反,nth-of-type(2)选择器同时选择了<div style="height: 50px;"></div>两次。

我以为.test input.two ~ div:nth-of-type(2)会从开始<input class="two" />,向下计数2个<div>标签,然后降落在第二个标签上?

这里发生了什么事?

showdev

nth-of-type()“根据给定类型的元素根据它们在一组同级兄弟中的位置来匹配”。您的代码选择的<div>父元素之前的,input.two 并且也是第二个<div>同级。

在您的情况下,您可以考虑使用相邻的同级组合器在下面,我选择<div>紧随其后的.one(红色)和<div>紧随<div>其后的.two(蓝色)。

.one + div {
  background-color: red;
}

.two + div + div {
  background-color: blue;
}
<form class="test">
  <input class="one" value="one">
  <div>A</div>
  <input class="two" value="two">
  <div>B</div>
  <div>C</div>
</form>


只是为了好玩,这里有一个示例,nth-of-type通过将元素分组到单独的父容器中来帮助可视化

.one ~ div:nth-of-type(1) {
  background-color: red;
}

.two ~ div:nth-of-type(2) {
  background-color: blue;
}
<form class="test">
  <div>
    <input class="one" value="one">
    <div>A</div>
  </div>
  <div>
    <input class="two" value="two">
    <div>B</div>
    <div>C</div>
  </div>
</form>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章