Random color from array in Sass [duplicate]

2019-04-21 14:02发布

问题:

This question already has an answer here:

  • SASS: randomly pick background-image from a list 1 answer

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

回答1:

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.

Interesting note: the Sass documentation states that random($limit) "[returns] an integer between 1 and $limit, inclusive of 1 but not $limit." However, if you use nth($colors, random(length($colors) + 1)) in your CodePen demo to "make up for" the random() function not choosing the highest index, you are liable to get an error for using an index out of bounds. This would suggest that random() does indeed include $limit.



标签: random sass