I have a responsive grid layout. There can be any number of columns depending on the window width.
I am trying to make the grid have a checkered pattern, so I use the odd
and even
selectors to color the grid cells.
But it only works when the number of columns is odd. When the number of columns is even, it becomes a striped pattern.
Is there a CSS property/selector to solve this, or a better way to do it?
Here's the simplified code of my project showing the problem:
.grid {
display: grid;
counter-reset: spans;
grid-template-columns: repeat(var(--cols), 1fr);
grid-gap: 1px;
}
.grid > * {
counter-increment: spans;
text-align: center;
padding: 10px 0;
color: #fff;
}
.grid > *::after {
content: counter(spans);
}
/* Coloring */
.grid > *:nth-child(odd) {
background-color: #789;
}
.grid > *:not(:nth-child(odd)) {
background-color: #567;
}
<h2>Works when columns are odd</h2>
<div class="grid" style="--cols: 5;">
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
<h2>Doesn't work while even</h2>
<div class="grid" style="--cols: 4;">
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>