2

For example, something like:

div {
   margin-left: random(-100, 100);
}
Alexcamostyle
  • 3,053
  • 4
  • 12
  • 12

2 Answers2

5

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
  • 219,308
  • 53
  • 366
  • 287
1

Dont think CSS has that capability but LESS will help

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

Lucky Chingi
  • 2,222
  • 1
  • 9
  • 15