Bram
Bram

Reputation: 283

CSS nth-child: every 4th, 11th, 18th etc

I have the following div HTML-structure:

etc.

So, after 3 times a, comes 4 times b. I want to grab every B-element with a css nth-child selector. I tried nth-child:(4n + 3), but this didn't work out. Should this be possible with pure css, or do I have to use javascript.

I assume that, if this is possible with css, I would have declare 4 css-selectors.

Thank you!

Upvotes: 2

Views: 982

Answers (2)

Nenad Vracar
Nenad Vracar

Reputation: 122047

You can use li:nth-child(7n+4), li:nth-child(7n+5) ... where li:nth-child(7n+4) will match 4, 11, 18... and li:nth-child(7n+5) will match 5, 12, 19 etc.

li:nth-child(7n+4), li:nth-child(7n+5), li:nth-child(7n+6), li:nth-child(7n+7) {
  font-weight: bold;
}
<ol><li>Li</li><li>Li</li><li>Li</li><li>Li</li><li>Li</li><li>Li</li><li>Li</li><li>Li</li><li>Li</li><li>Li</li><li>Li</li><li>Li</li><li>Li</li><li>Li</li><li>Li</li><li>Li</li>
</ol>

You could also use li:nth-child(7n), li:nth-child(7n-1) ...

li:nth-child(7n), li:nth-child(7n-1), li:nth-child(7n-2), li:nth-child(7n-3) {
  font-weight: bold;
}
<ol><li>Li</li><li>Li</li><li>Li</li><li>Li</li><li>Li</li><li>Li</li><li>Li</li><li>Li</li><li>Li</li><li>Li</li><li>Li</li><li>Li</li><li>Li</li><li>Li</li><li>Li</li><li>Li</li>
</ol>

Upvotes: 2

Vucko
Vucko

Reputation: 20834

@NenadVracar's answer is correct, but here's a alternative using adjacent sibling selector:

li:nth-child(7n+4),
li:nth-child(7n+4) + li,
li:nth-child(7n+4) + li + li,
li:nth-child(7n+4) + li + li + li {
  color: red;
}
<ul>
  <li>a</li>
  <li>a</li>
  <li>a</li>
  <li>b</li>
  <li>b</li>
  <li>b</li>
  <li>b</li>
  <li>a</li>
  <li>a</li>
  <li>a</li>
  <li>b</li>
  <li>b</li>
  <li>b</li>
  <li>b</li>
  <li>a</li>
  <li>a</li>
  <li>a</li>
  <li>b</li>
  <li>b</li>
  <li>b</li>
  <li>b</li>
</ul>

Upvotes: 1

Related Questions