Style every third element?

How can I style every third element with plain CSS.

I have seen questions like this, but they involve javascript. I want a plain CSS solution. I know I can use even or odd with :nth-child but :nth-child(third) doesn’t work neither does :nth-child(3)

Example:

<section>
  <div class="someclass"></div> STYLE
  <div id="someId"></div> DON'T STYLE
  <div class="someotherclass"></div> DON'T STYLE
  <div id="someotherId"></div> STYLE
  <div class="someclass"></div> DON'T STYLE
  <div id="someId"></div> DON'T STYLE
  <div class="someotherclass"></div> STYLE
</section>

Is this possible with CSS - no javascript or jQuery?


solution

This is possible with pure CSS. No javascript needed.

Use the nth-child selector.1

section > div:nth-child(3n+1) {
  background:red;
}

Where ‘1’ is where the style starts, and 3 indicates that it should style every third element. It is explained much better here.

jsFiddle demo here.


1Note - as other people have mentioned this is not fully supported by IE8 and down.