5

For example, something like:

div {
   margin-left: random(-100, 100);
}
Alexcamostyle
  • 3,623
  • 4
  • 14
  • 13
  • Why can't you use javascrtipt? – pppery Nov 14 '15 at 02:08
  • 1
    @ppperry: I can, but it just seems rather inefficient to me. There should be a way to generate random numbers in CSS, like how you can do math in it with `Calc()`. – Alexcamostyle Nov 14 '15 at 02:11
  • 1
    Exactly what you're doing isn't possible in pure CSS, but [something similar is](http://codepen.io/Zeaklous/pen/BQjGzv) :P – Zach Saucier Nov 15 '16 at 19:56
  • If this was possible, then on every browser repaint the CSS might get re-evaluated and create a new random number, and your layout would move all over the place constantly, for example, when resizing the page/area or when any repaint is caused – vsync Nov 17 '22 at 08:56

3 Answers3

6

There is currently no way to do this in pure CSS, however if you're using a CSS pre-processor, such as LESS, then you can do the following:

@randomMargin: `Math.round(Math.random() * 100)`;

div {
  margin-left: ~'@{randomMargin}px';
}

The reason this works is because LESS will evaluate JavaScript expressions.

If you want to break it into a random mixin/function, you could use:

.random(@min, @max) {
  @random: `Math.round(Math.random() * (@{max} - @{min}) + @{min})`;
}

div {
  .random(-100, 100);
  margin-left: ~'@{random}px';
}

Which will compile with a different margin-left value each time:

div {
  margin-left: 18px;
}

However, I am not sure how practical this would be in a production environment since your CSS should already be compiled/minified rather than compiled on the fly. Therefore you should just use straight JavaScript in order to achieve this.

Community
  • 1
  • 1
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
2

You can set a random number as a CSS property with JavaScript:

let el = document.getElementById('foo');
el.style.setProperty('--rand', Math.random());

Then you can use that random number in your CSS, for example a random color:

#foo {
  --rand: 0.5; /* will be a random number from 0 to 1 set by javascript */
  --hue: calc(255 * var(--rand));
  background-color: hsl(var(--hue), 67%, 57%);
}

Or a random shade of green:

#foo {
  --rand: 0.5; /* will be a random number from 0 to 1 set by javascript */
  --greenHue: calc(70 + (30 * var(--rand)));
  --greenSaturation: calc(50% + (30% * var(--rand)));
  --greenLevel: calc(25% + (5% * var(--rand)));
  background-color: hsl(var(--greenHue), var(--greenSaturation), var(--greenLevel));greenLevel));
}

For more variation, set multiple random number variables. Also remember variables are inherited. And they can be used in keyframe animations/etc.

Abhi Beckert
  • 32,787
  • 12
  • 83
  • 110
1

Dont think CSS has that capability but LESS will help

http://csspre.com/random-numbers/

Lucky Chingi
  • 2,248
  • 1
  • 10
  • 15