HiveBrain v1.2.0
Get Started
← Back to all entries
patternhtmlMinor

CSS3 Selectors for achievements

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
css3forachievementsselectors

Problem

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







Testing...






Testing...








Testing...






Testing...






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;
}

Solution

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;
}

Code Snippets

.achievements :nth-child(even) :nth-child(odd) .achievement
.achievement {
  background: toggle(#ccc, #5891bc, #96c3e6, #d3dfe7);
}
:nth-of-type(n4+1 of .achievement) {
  background: #5891bc;
}

Context

StackExchange Code Review Q#23880, answer score: 3

Revisions (0)

No revisions yet.