DEV Community

Dev Ieffe
Dev Ieffe

Posted on • Edited on

Random numbers in CSS?

A built-in rand function in CSS, something like rand() that mirrors Math.random() in JavaScript would unlock an expressive, zero-JS design patterns. We’ve got rand() in Sass, but it’s compile-time only: it makes a single value into the output CSS, so you don’t get per-render or per-interaction randomness. You can also hack randomness into CSS through small JavaScript snippets that set custom properties, but that adds script weight, timing concerns, and complexity that feels out of place for purely presentational effects.

A native, runtime CSS rand()—usable anywhere a number is allowed, just like calc(), would let authors create lightweight, dynamic visuals without leaving stylesheets.

Imagine:

  • Micro-variations for “organic” UIs: slightly jittered shadows, random star fields, confetti, particle offsets.
  • Staggered animations without JS: animation-delay: rand(0s, 300ms); so every card starts a bit differently.
  • Procedural layouts: randomized background positions, gradient angles, or decorative transforms.
  • Subtle theming: tiny, bounded hue or lightness shifts for a living brand texture.

Possible syntax ideas (just examples):

  • rand() → 0…1 float
  • rand(10) → 0…10 float
  • rand(2px, 8px) → 2px…8px float
  • rand([1,2,3,5]) → pick from a discrete set
  • Seeded/locked variants: rand(… / seed(<identifier>)) for determinism across renders.

Where it would fit

Anywhere calc() works today: lengths, angles, colors (via functions), durations, delays, filter parameters, etc. Combined with custom properties, authors could scope randomness and tweak ranges without refactoring selectors.

We can keep using Sass for static variation or JS for dynamic variation, but neither hits the sweet spot of CSS-native, declarative, lightweight randomness. A first-class rand() with guardrails (ranges, units, seeding) and respect for user preferences feels as overdue and broadly useful as calc() was when it arrived.

Top comments (3)

Collapse
 
afif profile image
Temani Afif

github.com/w3c/csswg-drafts/issues... .. it will come one day
Maybe you don't know it but we already have a lot of Math in CSS in addition to calc()
w3.org/TR/css-values-4/#round-func
and this one w3.org/TR/css-values-4/#toggle-not...

Collapse
 
moopet profile image
Ben Sinclair

Can you think of an example of when it would be useful?

Collapse
 
devy profile image
Dev Ieffe

It's e.g. when create a class for a design element that is likely to have varied sizes like a dashboard with sticky notes that aren't all the same size.
.random { width: rand(Npx,Mpx,t) } N=min, M=max, t=level (step) of randomization, etc.
Each time the page loads, the user has slightly another look.