I would like to find a way to display some colors to div following a pattern.
I found a trick using modulo but it doesn\'t seems to work with CSS...
So, as i
As mentioned here, :nth-child()
does not support modulo operations. That said, this problem can still be solved using :nth-child()
.
We can see that the diff between each states are : 7 then 5 then 7 then 5 ...
The sum of 5 and 7 is 12. What you have, essentially, are two sequences with intervals of 12, just with slightly different starting points such that the difference between every two points alternates between 5 and 7. Here's a diagram to show you what I mean:
|---------------- 12 ----------------|--------------- 12 ----------------| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |-----------------12-----------------| |--------- 7 --------|------ 5 ------|--------- 7 --------|------ 5 -----|
With this in mind, for the sequence that starts with 1 followed by 8, use div:nth-child(12n+1)
and div:nth-child(12n+8)
. The same follows with the other sequences.
Thus:
div {
height: 40px;
}
/* 1, 8, 13, 20, 25... */
div:nth-child(12n+1),
div:nth-child(12n+8) {
background-color: blue;
}
/* 4, 9, 16, 21... */
div:nth-child(12n+4),
div:nth-child(12n+9) {
background-color: green;
}
/* 5, 12, 17, 24... */
div:nth-child(12n+5),
/* Note: 12n+12, 12n+0, and 12n are all equivalent */
div:nth-child(12n+12) {
background-color: orange;
}
blue
white
white
green
orange
white
white
blue
green
white
white
orange
blue
white
white
green
orange
white
white
blue
green
white
white
orange