Heads up! This blog post hasn't been updated in over 2 years. CodePen is an ever changing place, so if this post references features, you're probably better off checking the docs. Get in touch with support if you have further questions.
UPDATE: Sass now has a random()
function natively built in, so we removed our custom function. The only difference is that the native function starts at 1 instead of 0, so be aware of that with older Pens that used it.
Have you ever wished you could use a random number in CSS? Alas, it isn’t possible with straight CSS. But fortunately here on CodePen you can author CSS in Sass if you choose. Sass runs through a Ruby-based compiler before getting turned into regular CSS. That means we can add things do it to make more things possible. In this case, an all-new random()
function for returning random numbers!
You use it like this:
.column {
height: random(300) + px;
}
And you’ll get something like:
.column {
height: 123px;
}
in the actual CSS. You can see what you get by clicking on “CSS” in the header of that editor to see the compiled code.
random()
will return a number between 1-100 by itself, or you pass in a single integer parameter to define the upper limit. random(500)
will return a number between 1-500.
See the Pen Random() function in Sass by Chris Coyier (@chriscoyier) on CodePen
Negative Numbers
Sass can do math, so if you can manipulate the random number howeever you wish after it has been generated. If you need a random number between -100 and 100, you could do random(200) - 100
See the Pen enHjw by Chris Coyier (@chriscoyier) on CodePen
Random at Runtime
Note that the random number that is generated by random() happens when Sass is compiled. When working in the Editor View, that happens pretty regularly: every time you update the Sass code. But when viewing the page in, for instance, Full Page View, we don’t re-compile the Sass for each refresh. That is just displaying the CSS that has already been compiled and cached.
On Exporting
Just a quick note that we leave the random() function in your exported Pens. If you were to then try to compile that Sass with an out-of-the-box Sass compiler, it will error because out-of-the-box Sass doesn’t know what random() is. You’ll need to remove it or alter Sass for it to compile.
Your .css file will work, because it will contain the randomly generated number.
Enjoy! Can’t wait to see how you folks use it for creative stuff.