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. A star field with CSS and HTML <html> <body> <div class=star></div> <div class=star></div> … <div class=star></div> </body> </html> We’ll start by creating an HTML element for each star. Then paint the sky and style the stars with white circles of any size for now to act as stars. Setting the star to be fixed positioning will make it easy to place them randomly. body { background-color: black; } .star { background-color: white; border-radius: 50%; aspect-ratio: 1/1; width: 3px; position: fixed; } Now we’ll distribute the stars by setting the top and left properties to a random value, in this case 0-100% for top (Y-axis) and a separate random value for left (X-axis). By default, each random() function will generate different random values using a different random base value generated from a uniform distribution. .star { background-color: white; bor...
First seen: 2025-08-24 03:56
Last seen: 2025-08-24 16:10