42

Question: Is there is any way (in JS) to create a random color code using just bright colors, or pastel colors?

I am building a simple website that gives a random quote when I click a button, and with that, the background color changes. The thing is that sometimes the background color is too dark and the font is black, and consequently the person can't read the quote.

I found this code to generate a random color. I tried to edit to get only the strings A to F, but no success:

'#'+((1<<24)*(Math.random()+1)|0).toString(16).substr(1)
2
  • 1
    Use hsl() color and randomize just the Hue after finding optimal Saturation and Luminosity values jsfiddle.net/sva8ckpy
    – pawel
    Commented Apr 3, 2017 at 21:01
  • 1
    I'd guess '#'+((1<<24)*(Math.random()+1)|0xc0c0c0).toString(16).substr(1) might do the trick -- it should constrain every component to being in the range 0xc0-0xff but I don't know javascript so really anything at all could happen. 0x808080 allows more variation, but it might be too much. If you need more flexibility then you'll want one of the more complete answers given by people who probably know javascript.
    – sh1
    Commented Apr 4, 2017 at 3:23

3 Answers 3

94

HSL Colors

Using HSL Colors colors may be the easiest. HSL color values are specified in CSS as

hsl( hue, saturation%, lightness%)

where hue is in range 0-360 (without a unit marker when using degrees), and both saturation and lightness are percentages 0-100 with a trailing % sign.

Note

  • "Bright" colors refer to the colors of an RGB color wheel formed by starting at red and then blending pure red into green, pure green into blue, and finally pure blue back into red again.

  • In HSL color space, bright colors are represented by a hue based on their position on the color wheel with 100% saturation and a lightness value of 50%:

    hue 0HSL saturated color circle ◀ hue 360
    saturation: 100%
    lightness: 50%

  • Colors blend with white - and become more "pastel" as lightness increases above 50%. A lightness value of 100% creates white regardless of what the values of hue and saturation are.

  • Colors blend with grey as the saturation decreases and become more washed out depending on how low the saturation gets. A saturation value of 0% creates a grey-scale tone based on lightness alone.

  • Colors blend with black as lightness decreases below 50%. A lightness value of 0% creates black no matter what the hue and saturation values are.

Warning

The human eye is least sensitive to the color blue. Black text on a blue background - or blue over black - is harder to read in comparison to other colors. If this becomes an issue for random color selection, example 2 shows one way to compensate.


Example 1: Some random pastel colors with saturation in range 25-95% and lightness in range 85-95%:

function getColor(){ 
  return "hsl(" + 360 * Math.random() + ',' +
             (25 + 70 * Math.random()) + '%,' + 
             (85 + 10 * Math.random()) + '%)'
}


// Generate 20 colors
for( var i = 20; i--; ){
  var item = document.createElement('div')
  item.style.cssText = `
    display:inline-block; 
    padding: 2em;
    margin:5px; 
    border-radius:50%;
    background: ${getColor()};
  `
  document.body.appendChild(item);
}


Example 2: This example demonstrates adjusting colors for the eye's lack of sensitivity to blue. It generates a boxed set of letters colored with hues in the range 0 to 340 presented on a black background.

"use strict";

// individual letter classes:
function letterCSS(letter, i, length, blueBoost) {
    let hue = Math.floor( i/length * 341); // between 0 and 340
    let saturation = 100;
    let lightness = 50;

    // color adjustment:
    if( blueBoost && hue > 215 && hue < 265) {
         const gain = 20;
         let blueness = 1 - Math.abs( hue-240)/25;
         let change  = Math.floor( gain * blueness);
         lightness += change;
         saturation -= change;
    }
    let hsl = `hsl(${hue}, ${saturation}%, ${lightness}%)`;

  return `.${letter} {
  color: ${hsl};
  border-color: ${hsl};
  background-color: black;
}
`   ;
}

// generate and display boxed letters of the alphabet
function letterBlocks() {
    let letters = Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
    let cssText = "";
    let html = ""
    let blueBoost = document.getElementById("boost").checked;
    letters.forEach( (letter, i, a) => {
       cssText += letterCSS( letter, i, a.length, blueBoost);
       html  += ` <span class="letter ${letter}">${letter}<\/span> `;
    });
    let style = document.createElement("style");
    style.textContent = cssText;
    document.body.appendChild(style);
    let p = document.getElementById("blocks");
    p.innerHTML = html;
}
#blocks {
  line-height: 2.5rem;
}
.letter {
  display: inline-block;
  text-align: center;
  line-height: 2rem;
  font-size: 1.5rem;
  height: 2rem;
  width: 2rem;
  font-family: sans-serif;
  font-weight: bold;
  border-width: 0.125rem;
  border-style: solid;
  border-radius: 0.25rem;
}
<button type="button" onclick="letterBlocks()">Generate Letter Blocks</button><label>
- optionally lighten colors near pure blue:<input type="checkbox" id="boost">
</label>
<p id="blocks"></p>

Letter colors start out with full saturation and 50% lightness. Check the option box and click the button to adjust colors close to blue by increasing lightness and decreasing saturation.

  • "Close to blue" is hard coded to mean within 25 degree units of hue value 240,
  • The maximum adjustment amount is set by gain to 20 percentage units,
  • Demonstration code. Real code and adjustment values would be altered on a case by case basis depending on why and how color adjustments are being made.
1
  • Wow, this explanation blew my mind over the rooftop, thanks a lot for this. Commented Jan 28, 2021 at 16:17
23

By randomizing only the hue, it's faster.

HSLA colors are a composition of Hue, Saturation, Lightness and Alpha.

Adjust the Lightness eq: 72% to adjust the whole pastel set.

function randomHSLA(){
    return `hsla(${~~(360 * Math.random())}, 70%,  72%, 0.8)`
}

rdm.onclick = () => document.body.style.background = randomHSLA()
rdm.click()
<button id="rdm">Random pastel color!</button>

2

You could choose among lighter colours by appropriately setting the background-color property using rgb.
rgb(0,0,0) is black, while rgb(255,255,255) is white. You could therefore use random values which are closer to (but not higher than) 255.
An example (using JQuery):

 var rand = Math.floor(Math.random() * 10);
 var colorQ = "rgb(" + (215 - rand * 3) + "," + (185 - rand * 5) + "," + (185 - rand * 10) + " )"; 
 $("body").css("background-color", colorQ);

You can play around with the values until you find the colours that you prefer - keep in mind that the closer the 3 rgb values are to each other, the closer your colour will be to grey. E.g. rgb(100,100,100), rgb(221,221,221) and rgb(133,133,133) are all shades of grey. What changes is how light your grey will be.

Not the answer you're looking for? Browse other questions tagged or ask your own question.