如何在CSS中只选择一些孩子?

Joh*_*ohn 3 css css-selectors

我的HTML中有一些div,动态数量的div

如何只选择div 2,5,8,11?

我试过这个,:nth-child(2n+3)但不完全是我需要的

这是代码:

<!DOCTYPE html>
<html>
  <head>
      <style>
          .a:nth-child(2n+3) { background:#ff0000; }
      </style>
  </head>
  <body>
    <p class="a">The first paragraph.</p>
    <p class="a">The second paragraph.</p>
    <p class="a">The third paragraph.</p>
    <p class="a">The fourth paragraph.</p>
    <p class="a">The fifth paragraph.</p>
    <p class="a">The sixth paragraph.</p>
    <p class="a">The seventh paragraph.</p>
    <p class="a">The eight paragraph.</p>
    <p class="a">The ninth paragraph.</p>
    <p class="a">The seventh paragraph.</p>
    <p class="a">The eight paragraph.</p>
    <p class="a">The ninth paragraph.</p>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

Dan*_*eld 11

编辑如果只需要2,5,8,11那么答案是:

p:nth-child(3n+2)
{
   background: #ccc;
}
Run Code Online (Sandbox Code Playgroud)


要选择第2,3,5,8,11段:

p:nth-child(3n+2),p:nth-child(3)
{
   background: #ccc;
}
Run Code Online (Sandbox Code Playgroud)

小提琴

我必须分别添加p:nth-​​child(3)因为它不适合每次+3的一般模式.