Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random color from array in Sass [duplicate]

Tags:

random

sass

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

like image 985
Niall Thompson Avatar asked Nov 14 '14 03:11

Niall Thompson


1 Answers

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.

like image 104
AJ Foster Avatar answered Sep 21 '22 23:09

AJ Foster