skip navigation

Target Grid Rows

So recently I had problem where I wanted to target every other row in a grid layout.

This is sometimes called the stripped effect and it’s commonly used in tables or any recurring block level element like paragraphs using the nth-child or selector. This selector can select odd or even elements easily like so: tr:nth-child(odd) would select every other table row beginning with the first one.

However when it comes to grid layouts there is no way to target a row because there is no specific markup in the HTML to target. The only thing you can target is the individual grid items, the child elements of your grid container.

However in some cases, specifically where you have a fixed number of columns, you can target the rows—though it wasn’t immediately obvious to me at first.

I had a 7 column grid so I wanted to target the first 7 items, the third 7 and so on. There are pretty complex ways to chain nth-child selectors together but I couldn’t figure out a solution.

It turned out I had been thinking about the problem in the wrong way. I was trying to do something targetting every 7 divs when I should have been thinking in terms of 14. The first 7 items were one colour and the next 7 were a different colour so 7 + 7 = 14.

Selecting every other row of a 7 column grid that covers an infinite number of rows.

div:nth-child(14n+1),
div:nth-child(14n+2),
div:nth-child(14n+3),
div:nth-child(14n+4),
div:nth-child(14n+5),
div:nth-child(14n+6),
div:nth-child(14n+7) {
    background-color: orange;
}

So it’s a bit on the verbose side and perhaps there’s a better way though the simplicity of each line shouldn’t mean there are any browser issues. This code will carry on repeating indefinitely.