How do I color alternate rows in a CSS Grid layout?

I have a CSS grid of 5 columns, not collapsing at smaller screen widths. It’s around 80 rows high.

How do color alternate rows other than by hand? I thought I would add an opacity to alternate colors to preserve the row colors I have now.

Assuming you are using CSS Grid then you could use the nth-child selector and target blocks of 5 like this.

.grid > div:nth-child(10n + 6),
.grid > div:nth-child(10n + 7),
.grid > div:nth-child(10n + 8),
.grid > div:nth-child(10n + 9),
.grid > div:nth-child(10n + 10) {
  background:rgba(0,0,0,0.5);
}

If you are using some other type of grid with specific rows then you could target odd rows instead,

3 Likes

This works! However, can I override certain cells, such as the left column, so they retain their coloring?

This is a timeline going down, and the left column indicate time ranges and important events.

Hi,

Yes, but you could also exclude them like e.g. for the left column with @PaulOB posted code as an example:

/* .grid > div:nth-child(10n + 6), */
.grid > div:nth-child(10n + 7),
.grid > div:nth-child(10n + 8),
.grid > div:nth-child(10n + 9),
.grid > div:nth-child(10n + 10) {
  background:rgba(0,0,0,0.5);
}
2 Likes

Perfect! Thanks!

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.