Home > Web Front-end > CSS Tutorial > How to Randomly Select Background Images in CSS with SASS?

How to Randomly Select Background Images in CSS with SASS?

Patricia Arquette
Release: 2024-11-20 12:32:12
Original
298 people have browsed it

How to Randomly Select Background Images in CSS with SASS?

Randomizing Background Images with SASS

If you need to output CSS with a randomly selected background image from a list, SASS provides an effective solution. With the introduction of the random function in Sass v3.3.0, you can easily achieve this random selection.

Implementation

To implement random background image selection, you'll need to define a list of images ($list) and a variable ($imgKey) for the random function:

$imgKey: random(5);

$list: apple, banana, cherry, durian, eggplant;
Copy after login

In your CSS, use the nth() function to select the appropriate image based on the randomized key:

#footer-widgets .container .row {
    background-image: url("/images/#{$nth($list, $imgKey)}.jpg");
    ...
}
Copy after login

Live Example

Visit the live example at http://sassmeister.com/gist/8966210 to see this technique in action.

Note: Remember that the random value will only change when the Sass is compiled, which may not occur every time your page is accessed.

The above is the detailed content of How to Randomly Select Background Images in CSS with SASS?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template