CSS3 Selectors for achievements I'm trying to change the background color of each .achievement div. The content is being generated dynamically so I can't add a class easily to each one.

I have it working with selectors like .achievements .grid-row:nth-child(odd) .col-1-2:nth-child(even) .achievement but they seem a little bloated. The problem I'm having is that the .achievement div is nested a few deep so I can't just use an :nth-child or :nth-of-type on it.

I'm just checking to see if there is a better way to select those that I'm missing out on.

jsFiddle

HTML



&lt;div class="achievements"&gt;

    &lt;div class="grid-row"&gt;
        &lt;div class="col-1-2"&gt;
            &lt;div class="achievement"&gt;
                &lt;p&gt;Testing...&lt;/p&gt;
            &lt;/div&gt;
        &lt;/div&gt;

        &lt;div class="col-1-2"&gt;
            &lt;div class="achievement"&gt;
                &lt;p&gt;Testing...&lt;/p&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;

    &lt;div class="grid-row"&gt;
        &lt;div class="col-1-2"&gt;
            &lt;div class="achievement"&gt;
                &lt;p&gt;Testing...&lt;/p&gt;
            &lt;/div&gt;
        &lt;/div&gt;

        &lt;div class="col-1-2"&gt;
            &lt;div class="achievement"&gt;
                &lt;p&gt;Testing...&lt;/p&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;

&lt;/div&gt;


CSS



.achievements .grid-row:nth-child(odd) .col-1-2:nth-child(even) .achievement {
    background: #5891bc;
}

.achievements .grid-row:nth-child(even) .col-1-2:nth-child(odd) .achievement {
    background: #96c3e6;
    color: #585858;
}

.achievements .grid-row:nth-child(even) .col-1-2:nth-child(even) .achievement {
    background: #d3dfe7;
    color: #585858;
}
You should probably take out the class selectors (.grid-row and .col-1-2) because nth-child doesn't respond to them (i.e. they're not doing anything):

.achievements :nth-child(even) :nth-child(odd) .achievement


In the future, CSS3's toggle() function (which cycles through values) could simplify things:

.achievement {
  background: toggle(#ccc, #5891bc, #96c3e6, #d3dfe7);
}


Sadly this isn't supported by any browsers yet. Also proposed is an :nth-match selector, which would let you do:

:nth-of-type(n4+1 of .achievement) {
  background: #5891bc;
}