Rolling the Dice with CSS random()
Random functions in programming languages are amazing. You can use them to generate variations, to make things feel spontaneous and fresh. Until now there was no way to create a random number in CSS. Now, the random()
function is on its way. You’ll be able to create a random animation delay, layout content at a random place on the screen, create a random color, or anything you want — all without any JavaScript.
The Basics
This new function has three arguments in this pattern: random(min, max, step)
. You state a minimum and maximum value to define the range from which the random number will be chosen. You can use any type of number (integer, percentage, length, angle, etc.) as long as all three arguments match. The step argument is optional, but is particularly useful for when you want to ensure round numbers.
For example, random(0, 100, 2)
will choose an even number between 0 and 100, while random(0turn, 1turn)
will be a fraction of a turn — basically, any decimal between 0 and 360 degrees.
Let’s take a look at how to use random()
by going through several demos. We’ll start by creating a field of stars out of HTML and CSS.