I want to specify an array of colours and then apply the colors randomly to a list.
So far I have it so that the colors will cycle through in order.
How can I randomise it?
Here is the Sass code so far:
$colors: red, orange, yellow, green, blue, purple;
@for $i from 1 through length($colors) {
li:nth-child(#{length($colors)}n+#{$i}) {
background: lighten(nth($colors, $i), 20%);
}
}
li {
list-style: none;
padding: 1em;
}
and the markup:
<ul>
<li>a</li>
<li>b</li>
<li>c</li>
<li>d</li>
<li>e</li>
<li>f</li>
<li>g</li>
<li>h</li>
<li>i</li>
<li>j</li>
<li>k</li>
<li>l</li>
</ul>
Example on Codepen: http://codepen.io/anon/pen/azbwJm
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With