Pseudo-Randomly Adding Illustrations With CSS

Eric Meyer has added a charming touch to his blog: between each post, one of five different illustrations appears. He built this by giving each illustration its own background image and then swapping between them using the nth-of-type selector.

Eric’s approach is what he calls pseudo-random — it looks random on the page, but the selection is actually deterministic. Still, the visual effect is effective: it breaks up the monotony of scrolling through a long page.

His core CSS pattern works 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);
}

If you find selector math confusing, CSS-Tricks has a handy :nth Tester that shows you exactly what strings like (2n+1) mean, in plain English, live on your own content.

Alternative methods exist. You can use random numbers in CSS: generate a variable in JavaScript and feed it to a CSS custom property. Or put all five images into a single sprite and change the background-position using that number.

There are no wrong answers here — just several clever ways to do the same delightful thing.