Home > Web Front-end > CSS Tutorial > How can I use SASS to randomly select a background image from a list of URLs?

How can I use SASS to randomly select a background image from a list of URLs?

Barbara Streisand
Release: 2024-11-17 00:14:03
Original
904 people have browsed it

How can I use SASS to randomly select a background image from a list of URLs?

Sass: Utilizing Random Background Images from a Designated List

SASS, a powerful CSS extension, provides advanced functionality for stylizing web pages. One such feature is the ability to dynamically select background images from a predetermined list. This article explores how to achieve this using SASS.

Question:

How can I use SASS to generate CSS code that randomly selects a background image from a provided list of URLs?

Answer:

To accomplish this task, harness the power of SASS's random() function, introduced in version 3.3.0. This function generates a random number within a specified range. By combining this functionality with a pre-defined list of image URLs, you can create dynamic background image assignments.

Consider the following SASS code snippet:

$imgKey: random(5);

$list: "image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg", "image5.jpg";
$nth: nth($list, $imgKey);

#footer-widgets .container .row {
    background-image: url("http://domain.com/blablabla/#{$nth}");
    background-position: right bottom;
    background-repeat: no-repeat;
}
Copy after login

In this example, the $list variable holds the list of image URLs. The $imgKey variable generates a random number between 1 and 5, representing the index of the image to be selected from the list. The nth($list, $imgKey) function extracts the image URL at that index.

Additional Notes:

  • The randomly selected background image will only change when the SASS is compiled. This may not happen every time a page is visited.
  • You can adjust the range of the random() function to match the number of images in your list.
  • Explore the SASS documentation for more information on the random() and nth() functions.

The above is the detailed content of How can I use SASS to randomly select a background image from a list of URLs?. 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