Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select only some children in CSS?

I have some divs in my HTML, a dynamic number of divs

How to select only divs 2,5,8,11 ?

I tried this :nth-child(2n+3) but is not exactly what I need

Here's the code:

<!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>
like image 842
John Avatar asked Dec 05 '22 09:12

John


1 Answers

EDIT If Only 2,5,8,11 is needed then the answer would be:

p:nth-child(3n+2)
{
   background: #ccc;
}


To select paragraphs 2, 3, 5, 8, 11:
p:nth-child(3n+2),p:nth-child(3)
{
   background: #ccc;
}

FIDDLE

I had to add p:nth-child(3) separately because it doesn't fit in the general pattern of +3 each time.

like image 170
Danield Avatar answered Feb 20 '23 23:02

Danield