Question

I'm trying to achieve a complicated type of n-th child selection with CSS and I'm not sure whether it's possible. If it is, might anyone know how to achieve it. (I found this guide but it doesn't seem to have a solution near what I need)

The desired result is a sequence that looks like this:

R B Y Y Y B R Y Y Y R B Y Y Y B R Y Y Y . . .

(This is clearer in the JS Fiddle here)

My CSS so far is:

div {
  float: left;
  width: 50px;
  height: 50px;
  background: grey;
  border: 1px solid black; 
}

div:nth-child(odd) {
    background: red;
}

div:nth-child(even) {
    background: blue;
}

div:nth-child(3n) {
    background: yellow;
}

But this is nowhere near right.

Can this be achieved?

Was it helpful?

Solution

Try:

div:nth-child(odd) {
    background: red;
}
div:nth-child(even) {
    background: blue;
}
div:nth-child(5n+3), div:nth-child(5n+4), div:nth-child(5n) {
    background: yellow;
}

DEMO

OTHER TIPS

Here is another solution:

div {
  ...
  background: yellow;
}
div:nth-child(10n + 1), div:nth-child(10n + 7) {
  background: red;
}

div:nth-child(10n + 2), div:nth-child(10n + 6) {
  background: blue;
}

Demo.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top