Edit: Sass introduced a module system. The random()
function is transitioning to math.random()
. See the documentation for the function and for the module system for more information.
First, I should state a reminder to everyone reading that Sass is precompiled into CSS; you cannot achieve random behavior "at runtime" (i.e. on page load) using Sass.
Sass has a random()
function that might interest you:
$colors: red, orange, yellow, green, blue, purple;
$repeat: 20 // How often you want the pattern to repeat.
// Warning: a higher number outputs more CSS.
@for $i from 1 through $repeat {
li:nth-child(#{length($colors)}n+#{$i}) {
background: lighten(nth($colors, random(length($colors))), 20%);
}
}
li {
list-style: none;
padding: 1em;
}
This chooses a random index of your $colors
array and uses the associated color.
Note: the documentation states that random($limit)
"returns a random whole number between 1 and $limit
." This includes $limit
as a possible value. As a result, if you use nth($colors, random(length($colors) + 1))
, you are liable to get an error for using an index out of bounds.