{"id":249849,"date":"2017-01-11T08:10:14","date_gmt":"2017-01-11T15:10:14","guid":{"rendered":"http:\/\/css-tricks.com\/?p=249849"},"modified":"2017-09-15T15:46:13","modified_gmt":"2017-09-15T22:46:13","slug":"random-numbers-css","status":"publish","type":"post","link":"https:\/\/css-tricks.com\/random-numbers-css\/","title":{"rendered":"Random Numbers in CSS"},"content":{"rendered":"

I stumbled into an interesting problem the other day. I wanted to animate an element with a random<\/em> animation-duration<\/code>. This was the non-randomized starting point:<\/p>\n

See the Pen Random numbers CSS #1<\/a> by Robin Rendle (@robinrendle<\/a>) on CodePen<\/a>.<\/p>\n

This is the CSS I wrote to make the animation:<\/p>\n

@keyframes flicker {\r\n  0% {\r\n    opacity: 1;\r\n  }\r\n  100% {\r\n    opacity: 0;\r\n  }\r\n}\r\n\r\n#red {\r\n  animation: flicker 2s ease alternate infinite;\r\n}<\/code><\/pre>\n

So far so good. But no randomization happening there, that’s a fixed 2 seconds.<\/p>\n

I wanted that animation time of 2 seconds to be random. I wanted to essentially write:<\/p>\n

.element {\r\n  animation: flicker $randomNumber alternate infinite;\r\n}<\/code><\/pre>\n

Where $randomNumber<\/code> is randomized programatically. <\/p>\n

CSS preprocessors like Sass do offer a random() function<\/a>. <\/p>\n

$randomNumber: random(5);\r\n\r\n.thing {\r\n  animation-duration: $randomNumber + s;\r\n}<\/code><\/pre>\n

That might be perfect for you, it wasn’t quite perfect for me. Random numbers generated during preprocessing have a big caveat:<\/p>\n

\n

random in Sass is like randomly choosing the name of a main character in a story. it's only random when written. it doesn't change.<\/p>\n

— jake albaugh (@jake_albaugh) December 29, 2016<\/a><\/p><\/blockquote>\n