CSS选择奇数/偶数类但在不同的父级下

时间:2018-03-07 17:38:13

标签: javascript jquery html css

将HTML模型说成如下:

<div class="wrapper">
    <div class="parent">
      <div class="target">text in even</div>
    </div>
    <div class="parent">
      <div class="target">text in odd</div>
    </div>
    <div class="parent">
      <div class="target">text in even</div>
    </div>
    <div class="parent">
      <div class="target">text in odd</div>
    </div>
</div>

我在jQuery中测试我们可以使用jQuery的even / odd()方法来选择目标类,如下所示:

> $(".target:even()")
> $(".target:odd()")

但CSS中有一种简单的方法吗?请注意这些.target类有不同的父级和nth-child()和nth-of-type()不起作用(如果我错了请纠正我。)

更新:我也尝试了以下但是对我不起作用。

.parent:nth-of-type(2n) target { }
.parent:nth-of-type(2n+1) target { }

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以将nth-child(odd) and nth-child(even)用于此

&#13;
&#13;
.parent:nth-child(even) .target{
color:green;
}

.parent:nth-child(odd) .target{
color:red;
}
&#13;
<div class="wrapper">
    <div class="parent">
      <div class="target">text in odd</div>
    </div>
    <div class="parent">
      <div class="target">text in even</div>
    </div>
    <div class="parent">
      <div class="target">text in odd</div>
    </div>
    <div class="parent">
      <div class="target">text in even</div>
    </div>
</div>
&#13;
&#13;
&#13;

P.S 您在使用nth-of-type时错过了.

&#13;
&#13;
.parent:nth-of-type(2n)  .target{
color:green;
}

.parent:nth-of-type(2n+1)  .target{
color:red;
}
&#13;
<div class="wrapper">
    <div class="parent">
      <div class="target">text in odd</div>
    </div>
    <div class="parent">
      <div class="target">text in even</div>
    </div>
    <div class="parent">
      <div class="target">text in odd</div>
    </div>
    <div class="parent">
      <div class="target">text in even</div>
    </div>
</div>
&#13;
&#13;
&#13;