bravokiloecho
bravokiloecho

Reputation: 1463

Complicated CSS n-th child selector

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?

Upvotes: 3

Views: 314

Answers (2)

laaposto
laaposto

Reputation: 12213

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

Upvotes: 8

King King
King King

Reputation: 63317

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.

Upvotes: 3

Related Questions