For example, something like:
div {
margin-left: random(-100, 100);
}
For example, something like:
div {
margin-left: random(-100, 100);
}
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.
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.