nth-of-type不起作用

时间:2018-03-22 13:16:59

标签: html css css3 css-selectors

我想在第二个活动类上应用一些CSS。一次只有两个元素可以有活动类。

我尝试过以下CSS选择器:

 .p .active:last-of-type
 .p .active:nth-of-type(2)

但他们都没有工作。请告诉我我做错了什么。

这是我的代码:



.p .active:nth-of-type(2){
   background: red;
}

<div class="p">
  <div class="a">The first paragraph.</div>
  <div class="a active">The second paragraph.</div>
  <div class="a active">The third paragraph.</div>
  <div class="a">The fourth paragraph.</div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:3)

CSS没有 native 工具如何做到这一点。一个小的hackish代码可能

.p .b ~ .b {background: red;} /* set properties to 2nd, 3rd, 4th, ... .b elements */
.p .b ~ .b ~ .b {background: none;}  /* reset properties to 3rd, 4th, ... .b elements */
<div class="p">
    <div class="a">The first paragraph.</div>
    <div class="a b">The second paragraph.</div>
    <div class="a b">The third paragraph.</div>
    <div class="a">The fourth paragraph.</div>
</div>

<br>

<div class="p">
    <div class="a">The first paragraph.</div>
    <div class="a b">The second paragraph.</div>
    <div class="a b">The third paragraph.</div>
    <div class="a b">The fourth paragraph.</div>
    <div class="a">The fifth paragraph.</div>
</div>