We have a series of items that are laid out in a rows in two-column display: grid
.
We also have 5 branded colors: orange, blue, yellow, green, pink.
The background colors of the rows should iterate over those colors in order, e.g.:
- Row 1: orange
- Row 2: blue
- Row 3: yellow
- Row 4: green
- Row 5: pink
- Row 6: (back to the first of the 5 colors) orange
- Row 7: blue
- …etc.
I know how to iterate over every one item using :nth-child(5n + 1)
, as shown in the snippet below. This works fine if we have a <table>
where each pair of items is enclosed in a <tr>
.
But in this case the items are not grouped, and we want to iterate over every two items. How do we accomplish the effect of coloring by row?
ul {
display: grid;
grid-auto-rows: 50px;
grid-template-columns: repeat(2, minmax(0, 1fr));
}
li:nth-child(5n + 1) {
background: orange;
}
li:nth-child(5n + 2) {
background: blue;
}
li:nth-child(5n + 3) {
background: yellow;
}
li:nth-child(5n + 4) {
background: green;
}
li:nth-child(5n + 5) {
background: pink;
}
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<ul>
2
Answers
One solution is to use
10n
instead of5n
, so the first two elements will beli:nth-child(10n + 1), li:nth-child(10n + 2)
You are using a fixed height for rows, so consider a gradient: