
CSS random()
The random() function generates a random value in CSS — no JavaScript, no inline styles. It’s part of the CSS Values Level 5 spec and brings controlled randomness directly into stylesheets.
.particle {
translate: random(0px, 300px) random(-150px, 150px);
opacity: random(0.3, 1);
scale: random(0.5, 1.5);
} Each element gets independently randomized values at parse time — great for scattered decorative elements, organic layouts, or generative patterns.
Syntax
random(<lower-bound>, <upper-bound>)
random(<lower-bound>, <upper-bound>, by <step>) The optional by parameter quantizes the output to discrete steps:
/* Picks from: 0, 25, 50, 75, or 100 */
opacity: random(0, 1, by 0.25);
/* Picks from multiples of 8px between 8px and 64px */
margin-inline-start: random(8px, 64px, by 8px); Per-Element vs Shared Randomness
By default, each element gets its own random value. Use random-caching-options to share a value across elements or tie it to a custom identifier:
/* All .dot elements share one random hue */
.dot {
background: oklch(65% 0.2 random(0deg, 360deg, per-element: false));
}
/* Each .dot gets its own hue */
.dot {
background: oklch(65% 0.2 random(0deg, 360deg));
} The default per-element: true behavior means the same rule produces different values on each element it matches.
Combining with Custom Properties
@property --rand-x {
syntax: "<length>";
inherits: false;
initial-value: 0px;
}
.confetti {
--rand-x: random(-50%, 50%);
--rand-delay: random(0s, 2s);
translate: var(--rand-x) -100%;
animation-delay: var(--rand-delay);
} Registering --rand-x with @property gives it a type so it can be interpolated in animations.
Generative Patterns
Scatter decorative elements without a JavaScript loop:
.star {
--size: random(4px, 16px, by 2px);
width: var(--size);
height: var(--size);
left: random(0%, 100%);
top: random(0%, 100%);
opacity: random(0.2, 0.9);
border-radius: 50%;
} Randomness and Re-renders
random() values are resolved at computed-value time and do not change on repaint or style recalculation. Values stay stable for the lifetime of the element. To re-randomize, force a style recalc by toggling a class or removing/re-adding the element.
Feature Detection
@supports (translate: random(0px, 10px)) {
/* random() is supported */
} const supported = CSS.supports("translate", "random(0px, 10px)"); random() is currently available in Chrome Canary behind a flag and is part of the CSS Values Level 5 specification.









