Pseudo-Randomly Adding Illustrations with CSS

Avatar of Robin Rendle
Robin Rendle on (Updated on )

Between each post of Eric Meyer’s blog there’s this rather lovely illustration that can randomly be one of these five options:

Eric made each illustration into a separate background image then switches out that image with the nth-of-type CSS property, like this:

.entry:nth-of-type(2n+1)::before {
   background-image: url(image-1.png);
}

.entry:nth-of-type(3n+1)::before {
   background-image: url(image-2.png);
}

.entry:nth-of-type(4n+1)::before {
   background-image: url(image-3.png);
}

.entry:nth-of-type(5n+1)::before {
   background-image: url(image-4.png);
}

This seems like a good time to plug our very own little :nth Tester tool. It definitely helps me understand what something like (2n+1) means in English. You can type in any string you like and see what effect that has on your site:

Anyway, back to Eric’s post. As he mentions, his technique is pseudo-random in that it looks like a random image on the page but it technically isn’t. Either way, I think it’s a really lovely technique! And it certainly breaks up the visual monotony that happens when you’re looking at a website for too long.

Here’s what it looks like in practice:

Lovely stuff!

Another way to do this is to use random numbers in CSS. For example, we could set a variable in JavaScript and then apply it with CSS custom properties. Or we could put all the images in a single sprite file and change the background-position based on a random number.

This is definitely one of those things in CSS where there are no wrong answers; just different ways to do the same awesome thing!