3
\$\begingroup\$

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

<div class="achievements">

    <div class="grid-row">
        <div class="col-1-2">
            <div class="achievement">
                <p>Testing...</p>
            </div>
        </div>

        <div class="col-1-2">
            <div class="achievement">
                <p>Testing...</p>
            </div>
        </div>
    </div>

    <div class="grid-row">
        <div class="col-1-2">
            <div class="achievement">
                <p>Testing...</p>
            </div>
        </div>

        <div class="col-1-2">
            <div class="achievement">
                <p>Testing...</p>
            </div>
        </div>
    </div>

</div>

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;
}
\$\endgroup\$
3
\$\begingroup\$

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;
}
\$\endgroup\$
  • \$\begingroup\$ You can use a class with :nth-child selectors, it just needs to have a parent. jsfiddle.net/ferne97/fZGvH/90. Thanks for the links, wasn't aware of those ones yet, they look cool. \$\endgroup\$ – ferne97 Mar 13 '13 at 22:44
  • \$\begingroup\$ No problem! Hmm nope, that doesn't work for me on the latest Chrome (25). It sort of works on FF/Safari, but it breaks if there are any sibling elements (which sort of defeats the point of using the class selector in the first place). \$\endgroup\$ – Alex Peattie Mar 14 '13 at 0:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.