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?

有帮助吗?

解决方案

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

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top