MultiformeIngegno MultiformeIngegno - 5 months ago 20
CSS Question

LESS (CSS): Pick random content from array

I'm trying to serve a random image picked from an array in Less.

Here's what I have so far:

@images = ['ancora.svg', 'timone.svg', 'corda.svg', 'bussola.svg'];
@randomimage: `images[Math.floor(Math.random() * images.length)]`;

#footer-widgets .container .row {
background: url("//website.com/path/@{randomimage}") no-repeat scroll right 60px bottom 40px rgba(0,0,0,0);
}


I think I'm doing some syntax error though. Is that the way to call a variable inside a url (
path/@{randomimage}
)?

Answer

An working example of your code can be found below:

@images: 'ancora.svg', 'timone.svg', 'corda.svg', 'bussola.svg';
@length: length(@images);
@random: `Math.ceil(Math.random() * (@{length}))`;
@randomimage: extract(@images,@random);

#footer-widgets .container .row {
    background: url("//website.com/path/@{randomimage}") no-repeat scroll right 60px bottom 40px rgba(0,0,0,0);
}

Notice that "array" in Less can be defined as lists, also see: Loop through array of values in LESS The first index of Less list is 1

Unless you compile your Less code client side (recompile the code for every request) you should take the comment of @Random-User into account. Indeed the compiled CSS is static and the randomize do not seems the make sense.