Different background color based on position

I wanted to have different background colors for post tiles for one of my webpages. The goal was to dynamically set a specific color since there will be more posts in the future. Here I’m going to show how to achieve this with CSS.


In the below example we have a grid with 4 columns. Tiles can have one of the three colors repeated in the same order.

The parent div has a “container” class. Child divs have “block” class. To achieve the above, you need to use nth-of-type pseudo-class. This pseudo-class will allow us to select an element based on it’s position among siblings of the same type.

For instance in our case .block:nth-of-type(3n+1) selects the first and the fourth tile. This selector: .block:nth-of-type(3n+2) selects the second and the fifth tile. The formula is: if you have three colors use 3n, if you have for example 5, then it’s 5n. I’ve added a working example on CodePen.

. . .

Yes, this stupid code works 💛

Leave a Comment