3

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?

2 Answers 2

8

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

0
3

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.

1
  • 2
    div { background: yellow } and remove last block. I see no reason to select divs for yellow explicitly.
    – Alexey Ten
    Apr 24, 2014 at 14:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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