← All posts

CSS random() Is Ready for Decoration, With a Fallback

CSS random() puts pseudo-random values in your stylesheet with no JavaScript. Here is where I'd use it and the fallback I wouldn't ship without.

I'm excited about CSS random(). It generates pseudo-random numbers right inside a stylesheet. I don't need JavaScript, server-side scripting, or a Sass loop baking a few hundred static values at build time.

Mat Marquis wrote a thorough breakdown of it on Piccalil.li, Understanding CSS random(). Most of his article explains how the browser decides when two calls share a value. By default every element gets its own value for each property and each call, and named keys let you widen that when you want things to match.

Where I'd use it

Anywhere a UI feels too rigid or too repetitive. Think of a grid of cards that all sit at the same angle, or a row of tags that all use the same tint. These are small touches, and writing JavaScript just to sprinkle a little variety on them has always felt like overkill to me. A script that walks the DOM and sets an inline style on every card is a lot of code for a two degree tilt.

.card {
  rotate: random(-3deg, 3deg);
}

Each card gets its own tilt from one line of CSS.

Don't ship it bare

Support is the catch. Safari has had it since 26.2, and Smashing Magazine reports Chrome is rolling it out in version 156. Firefox doesn't support it yet. Anyone on Firefox or an older Chrome or Safari gets nothing from that rule.

For a rotation that's harmless. It gets worse when random() drives something the layout depends on. Put it on opacity, a width, or a position, and an unsupported browser can end up with a broken layout or an element nobody can see.

The fix is old and boring. Declare a safe value first, then the random one.

.card {
  /* Fallback for Firefox & older browsers */
  rotate: 0deg;

  /* Progressive enhancement for supported browsers */
  rotate: random(-3deg, 3deg);
}

A browser that doesn't understand random() drops the second declaration and keeps the first. Supported browsers get the tilt. Everyone else gets straight cards, which is what they had before.

I'd start with decorative stuff where a fixed value is a perfectly good fallback. That's where random() pays off today. Save the layout-critical uses for when Firefox ships it.

Sources