How to return hexadecimal color randomly

Asked

Viewed 205 times

3

I’m wanting to each build change the css of my application randomly.

Example:

$menu-color: #0097a7; // retonar apenas uma cor
$menu-color: random(#0097a7,#FAFAFA,#7FB800); // retorna uma color aleatoria.

Since the Random returns only a random number this would not be the solution, as I could solve?

2 answers

2

A very simple way is to use rgb() instead of #hex:

$red: random(256)-1;
$green: random(256)-1;
$blue: random(256)-1;

And then:

color: rgb($red, $green, $blue);

Or

background-color: rgba($red, $green, $blue);

So in addition to having the randomness, you can "calibrate" the generated tones by dosing the RGB (red, green, blue) with different values if you want.

The curious thing is that SASS converts to #hex and/or default colors at the end. This blog gives some ideas of how to get around this if you want the output using rgb() literally.

  • I looked at this article before, but I found it a bit complicated, example: how to get from hexadecimal: #FAFAFA I will get red,green and blue from rgb?

1

Complementing the reply by @Bacco with the doubt of your comment. You can get again the red, green and blue as follows:

$hex: #FAFEF0;

red($hex); // 250

green($hex); // 254

blue($hex); // 240

The complete example:

$red: random(256) - 1;
$green: random(256) - 1;
$blue: random(256) - 1;

$hex: rgb($red, $green, $blue);

.color {
  color: $hex; /* Cor gerada randomicamente */
  background-color: rgba(red($hex), green($hex), blue($hex), .7);
}

You’d get something like this:

.color {
  color: #db7d39; /* Cor gerada randomicamente */
  background-color: rgba(219, 125, 57, 0.7);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.