W3C home > Mailing lists > Public > public-css-archive@w3.org > February 2019

Re: [csswg-drafts] [css-values] random() function (#2826)

From: Tommy Hodgins via GitHub <sysbot+gh@w3.org>
Date: Thu, 28 Feb 2019 19:21:55 +0000
To: public-css-archive@w3.org
Message-ID: <issue_comment.created-468402592-1551381714-sysbot+gh@w3.org>
I've been looking for something like `Math.random()` in CSS for a few years, and experimenting with different use cases and ways they can be achieved. If I were to set this up today I'd use CSS variables as the handoff between JavaScript and CSS, which also gives you full control over how and when these values are calculated. Here's a demo:

<div>I use random from CSS</div>
<div style="--random-bg: 360;">I use random from DOM</div>
<div class=load>I am randomized once per load event</div>
<div class=click>I am randomized once per click event</div>

  div {
    --random-bg: 360;
    background-color: hsl(calc(var(--random-bg) * 1deg), 75%, 50%);
  .load {
    --randomized-on-load: 360;
    background-color: hsl(calc(var(--randomized-on-load) * 1deg), 75%, 50%);
  .click {
    --randomized-on-click: 360;
    background-color: hsl(calc(var(--randomized-on-click) * 1deg), 75%, 50%);

<script type=module>
  import computedVariables from 'https://unpkg.com/computed-variables/index.es.js'

    value => Math.random() * value,

    value => Math.random() * value,

    value => Math.random() * value,

You can create a CSS variable like `--example: 10;` and use the Javascript function `value => Math.random() * value` to generate a random number between `0` and the supplied value. In this demo I've created a few different background colors and picked random numbers between 0 and 360. The next part is where the control comes in:

- you can have things calculated once per load
- you can have things calculated once per event (like every click event)
- the values cascade nicely in CSS and DOM exactly how you'd expect

It seems like everything people want is possible already! In the past I'd have said that this was a much-needed feature that should be added to CSS for animation and other things, but considering how flexible and powerful it is to use JavaScript's own `Math.random()` with styles by way of CSS variables I think a lot of that pressure is removed.

It's also easy to create random choice function in JavaScript that can pick randomly from a list of values given in CSS too, like `--choose: ['lime', 'hotpink']` and assign the chosen value to the CSS variable for CSS to make use of in styles.

GitHub Notification of comment by tomhodgins
Please view or discuss this issue at https://github.com/w3c/csswg-drafts/issues/2826#issuecomment-468402592 using your GitHub account
Received on Thursday, 28 February 2019 19:21:57 UTC

This archive was generated by hypermail 2.4.0 : Tuesday, 5 July 2022 06:41:44 UTC