Home > Article > Web Front-end > How to Randomly Select Background Images in SASS?
Dynamic Background Images in SASS Using Random Selection
To enhance the visual appeal of a website, it is common to incorporate background images. However, if you want to add a touch of variability to your designs, selecting images randomly from a list using SASS can be a powerful technique.
Objective:
Generate SASS code to randomly pick a background image from a predetermined list and insert it into a CSS selector.
Solution:
In recent versions of SASS, the random() function provides the ability to generate random numbers. By combining this with a list of image URLs stored in a variable, you can dynamically select a background image for your CSS rules.
Consider the following example:
$image-list: ( "url(domain.com/blablabla/image1.png)", "url(domain.com/blablabla/image2.png)", "url(domain.com/blablabla/image3.png)", "url(domain.com/blablabla/image4.png)", "url(domain.com/blablabla/image5.png)" ); $random-image: random(length($image-list)); #footer-widgets .container .row { background-image: nth($image-list, $random-image); }
In this example, a list of image URLs is stored in the $image-list variable. The random() function is used to generate a random integer between 1 and 5 (the length of the list). The nth() function is utilized to obtain the image URL at the specified random index.
The compiled CSS will include the randomly selected background image URL in the background-image property of the specified CSS selector. This code ensures that a different background image is used each time the SASS is compiled.
Considerations:
It's important to note that the random value is only generated during Sass compilation. This means that the background image will remain the same until the SASS is compiled again, regardless of page visits.
The above is the detailed content of How to Randomly Select Background Images in SASS?. For more information, please follow other related articles on the PHP Chinese website!