NewNode 26.14: mockResolvedValue and Friends in node:test →
w3/w3-tutorials

CSS random(): random sizes, colors and delays without JS

Chrome 156 and Safari 26.2 support random(), and Firefox 161 adds it on November 24. Scatter, size and stagger elements in pure CSS, share one value between properties, and keep screenshot tests stable.

Updated Nov 20, 20268 min readIntermediatechrome 157.0 · playwright 1.65.1 · node 22.22

Chrome 156 and Safari 26.2 can pick random values in CSS, and Firefox 161 adds random() on November 24. You can scatter decorations, vary sizes and stagger animations without JavaScript. Because the value never appears in your HTML, server-rendered markup stays identical on server and client. That avoids the hydration mismatches that Math.random() causes in a render function.

This guide builds a small star field and shows when two random() calls share a value. It also fixes the one place random CSS hurts: screenshot tests.

How random() works

random(min, max) returns a value between min and max. Both must be the same type: lengths, percentages, angles, times or plain numbers. An optional third argument is the step. random(0px, 100px, 25px) returns only 0, 25, 50, 75 or 100 pixels.

The browser picks the value when it computes styles. The value stays the same for the life of the page and changes on the next load. JavaScript sees the result through getComputedStyle(), like any other computed value.

1. Scatter dots across a box

Start with five empty elements:

index.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>CSS random() demo</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <div class="sky">
    <span class="dot"></span>
    <span class="dot"></span>
    <span class="dot"></span>
    <span class="dot"></span>
    <span class="dot"></span>
  </div>
</body>
</html>

Give each dot a random position, size and hue:

styles.css
body {
  margin: 0;
  background: #0b1020;
}

.sky {
  position: relative;
  height: 100vh;
  overflow: hidden;
}

.dot {
  position: absolute;
  top: random(0%, 100%);
  left: random(0%, 100%);
  width: random(4px, 24px);
  height: random(4px, 24px);
  border-radius: 50%;
  background: hsl(random(0, 360) 80% 70%);
}

Open the page and paste this into the DevTools console to see what the browser picked:

js
document.querySelectorAll(".dot").forEach((dot, i) => {
  const s = getComputedStyle(dot);
  console.log(i, s.width, s.height, s.top, s.left, s.backgroundColor);
});

In Chrome 157, with an 800×600 window:

text
0 14.75px 9.21875px 376.938px 202.016px rgb(117, 240, 227)
1 17.625px 16.1875px 584.828px 469.844px rgb(230, 117, 240)
2 8.60938px 21.0938px 492.438px 116.031px rgb(240, 236, 117)
3 19.7969px 8.4375px 581.609px 165.125px rgb(240, 117, 237)
4 14.7344px 10.7656px 286.188px 783.75px rgb(240, 233, 117)

Every value differs, and that is the problem. Each random() call rolls on its own, so width and height disagree and the dots come out as ovals.

2. Share one value between width and height

random() takes an optional first argument, the random key. It decides which calls share a value. Give width and height the same key, and stagger the animation while you're at it:

styles.css
.dot {
  position: absolute;
  top: random(0%, 100%);
  left: random(0%, 100%);
  width: random(--size element-scoped, 4px, 24px);
  height: random(--size element-scoped, 4px, 24px);
  border-radius: 50%;
  background: hsl(random(0, 360) 80% 70%);
  animation: twinkle 2s ease-in-out infinite alternate;
  animation-delay: random(0s, 2s, 0.25s);
}

@keyframes twinkle {
  to { opacity: 0.2; }
}

--size element-scoped means: on this element, every random() with the key --size gets the same value. Each dot is now a circle with its own size. The stepped animation-delay stops the dots from blinking in unison.

Log the size and delay:

js
document.querySelectorAll(".dot").forEach((dot, i) => {
  const s = getComputedStyle(dot);
  console.log(i, s.width, s.height, s.animationDelay);
});
text
0 19.3438px 19.3438px 0.25s
1 5.25px 5.25px 1.5s
2 7.21875px 7.21875px 0.75s
3 4.53125px 4.53125px 0.5s
4 21.7656px 21.7656px 1.5s

The values stay put. Reading them again returns the same numbers. A second rule that sets width: random(4px, 24px) again, such as a :hover state, keeps the old value. The default key is built from the property name and position, not from the selector (MDN explains the details). A reload picks new values.

3. Pick the right key

KeyShared across elementsShared across properties
none, or autoNoNo
element-scopedNoYes
property-scopedYesNo
--nameYesYes
--name element-scopedNoYes, between calls named --name
fixed 0.5Not random: always 50% of the way from min to max

To check it, read the width and height of two elements for each rule:

css
.auto { width: random(10px, 200px); height: random(10px, 200px); }
.el { width: random(element-scoped, 10px, 200px); height: random(element-scoped, 10px, 200px); }
.prop { width: random(property-scoped, 10px, 200px); height: random(property-scoped, 10px, 200px); }
.named { width: random(--size, 10px, 200px); height: random(--size, 10px, 200px); }
.named-el { width: random(--size element-scoped, 10px, 200px); height: random(--size element-scoped, 10px, 200px); }
.fixed { width: random(fixed 0.5, 10px, 200px); height: random(fixed 0.5, 10px, 200px); }

Chrome 157, as width x height, one pair per element:

text
auto      167.453px x 84.7969px | 75.1875px x 78.2656px
el        179.734px x 179.734px | 197.734px x 197.734px
prop      75.8281px x 57.9844px | 75.8281px x 57.9844px
named     56.0156px x 56.0156px | 56.0156px x 56.0156px
named-el  117.484px x 117.484px | 110.969px x 110.969px
fixed     105px x 105px | 105px x 105px

fixed 0.5 gives exactly 105px, halfway from 10px to 200px. A value that never changes sounds useless, but section 6 puts it to work in tests.

4. Store a value with @property

A custom property doesn't store the result. var(--s) pastes the text random(10px, 200px) wherever you use it, so each use rolls again. Register the property with @property and the browser computes the value once per element:

css
.unreg { --s: random(10px, 200px); width: var(--s); height: var(--s); }
@property --size-reg { syntax: "<length>"; inherits: false; initial-value: 0px; }
.reg { --size-reg: random(10px, 200px); width: var(--size-reg); height: var(--size-reg); }
text
unreg     173.016px x 70.8281px | 153.734px x 134.219px
reg       120.703px x 120.703px | 116.391px x 116.391px

The unregistered version produces rectangles. The registered one produces squares. Safari's 27.3 beta notes list "Added support for random() in custom properties", so check that version before you rely on the registered pattern in Safari.

5. Add a fallback

Until Firefox 161 reaches your users, some browsers will see random() as an invalid value. CSS ignores a declaration it can't parse. Put a fixed value first and the browser keeps it. For anything bigger, test support with @supports:

css
.card {
  rotate: 2deg;
  rotate: random(-6deg, 6deg);
}

@supports not (order: random(1, 2)) {
  .card:nth-child(odd) {
    rotate: -2deg;
  }
}

The test needs a property whose type matches the value. random(1, 2) is unitless, so it uses order, as MDN's examples do. CSS.supports("width", "random(1, 2)") returns false even in Chrome 157, because width needs a length.

Chrome 145, which predates random(), logs support and the three rotations:

text
false -2deg 2deg -2deg

Chrome 157:

text
true 0.202843deg -2.34392deg 0.225402deg

6. Keep screenshot tests stable

Every load picks new values, so a visual regression test fails on its second run even though nothing changed. This Playwright test has baseURL pointing at the demo in playwright.config.ts:

tests/sky.spec.ts
import { test, expect } from "@playwright/test";

test("home page", async ({ page }) => {
  await page.goto("/");
  await expect(page).toHaveScreenshot("home.png");
});
text
  ✘  1 tests/sky.spec.ts:3:1 › home page (695ms)

    Error: expect(page).toHaveScreenshot(expected) failed

      1206 pixels (ratio 0.01 of all image pixels) are different.

The quickest fix is to mask the random area. Playwright covers it with a pink box before comparing:

tests/sky.spec.ts
import { test, expect } from "@playwright/test";

test("home page", async ({ page }) => {
  await page.goto("/");
  await expect(page).toHaveScreenshot("home.png", {
    mask: [page.locator(".sky")],
  });
});

After updating the baseline with --update-snapshots, the test passed on three runs in a row with Playwright 1.65.1.

Masking hides the elements, so it can't catch a broken card layout. To keep them visible, pass the key through a variable that falls back to auto:

css
.card {
  rotate: random(var(--rand, auto), -6deg, 6deg);
}

In production --rand is unset, so the key is auto and every card gets its own tilt. In tests, inject a stylesheet that sets a fixed value:

tests/freeze-random.css
:root { --rand: fixed 0.5; }
tests/cards.spec.ts
import { test, expect } from "@playwright/test";

test("cards", async ({ page }) => {
  await page.goto("/cards.html");
  await expect(page).toHaveScreenshot("cards.png", {
    stylePath: "tests/freeze-random.css",
  });
});

Every card now renders at 0deg, halfway between -6deg and 6deg. This test passed on three reruns. Without stylePath, it failed with 3,811 different pixels. Every random() call that should freeze needs the variable as its key.

When not to use random()

  • Values that must stay the same per user, like an avatar color. random() picks again on every page load. Hash the user ID on the server instead.
  • Values your JavaScript depends on. You can read the result with getComputedStyle(), but if logic depends on it, generate the number in JavaScript.
  • Colors behind text. A random hue can push contrast below a readable level. Fix lightness and saturation, and keep random colors on decoration.
  • Layout that must not overlap. CSS doesn't check collisions, so random positions can land on top of content or each other. Keep it to decoration.

Next steps

Related tutorials