Generate Random Color with Pure CSS (No JavaScript)

CSS pick a random color from array

This is not possible in CSS, which is firmly deterministic. You could do this with client-side JavaScript, though:

var colors = ['#ff0000', '#00ff00', '#0000ff'];
var random_color = colors[Math.floor(Math.random() * colors.length)];
document.getElementById('title').style.color = random_color;

If you're using jQuery, the last line could become

$('#title').css('color', random_color);

create random rectangles with random colors without overlapping using javascript

A solution with canvas (so I understand the question).

With built-in collision detecting isInside().

Edit: Better random support, does not run forever, a hint from Drawing a 1px thick line in canvas creates a 2px thick line and a little bit from this answer Random Color generator in Javascript

function getRandomColor() {    var color = '#';    for (var i = 0; i < 6; i++) {        color += (Math.random() * 16 | 0).toString(16);    }    return color;}
function Point(x, y) { this.x = x; this.y = y;}
function Rectangle(p1, p2) { this.p1 = p1; this.p2 = p2;}
Rectangle.prototype.isInside = function (r) { function check(a, b) { return ( a.p1.x <= b.p1.x && b.p1.x <= a.p2.x && a.p1.y <= b.p1.y && b.p1.y <= a.p2.y || a.p1.x <= b.p2.x && b.p2.x <= a.p2.x && a.p1.y <= b.p2.y && b.p2.y <= a.p2.y || a.p1.x <= b.p2.x && b.p2.x <= a.p2.x && a.p1.y <= b.p1.y && b.p1.y <= a.p2.y || a.p1.x <= b.p1.x && b.p1.x <= a.p2.x && a.p1.y <= b.p2.y && b.p2.y <= a.p2.y ); } return check(this, r) || check(r, this);}
function generateRectangles() { function p() { return Math.random() * 300 | 0; } function s() { return 50 + Math.random() * 150 | 0; }
var rectangles = [], r, size, x, y, isInside, i, counter = 0;
for (i = 0; i < 20; i++) { counter = 0; do { counter++; x = p(); y = p(); size = s(); r = new Rectangle(new Point(x, y), new Point(x + size, y + size)); isInside = rectangles.some(function (a) { return a.isInside(r); }); } while (isInside && counter < 1000); counter < 1000 && rectangles.push(r); } return rectangles;}
function drawRectangles(rectangles) { var canvas = document.getElementById("canvas"), ctx = canvas.getContext("2d");
rectangles.forEach(function (a) { ctx.lineWidth = 1; ctx.strokeRect(a.p1.x + 0.5, a.p1.y + 0.5, a.p2.x - a.p1.x - 1, a.p2.y - a.p1.y - 1); ctx.fillStyle = getRandomColor(); ctx.fillRect(a.p1.x + 0.5, a.p1.y + 0.5, a.p2.x - a.p1.x - 1, a.p2.y - a.p1.y - 1); });}
var rectangles = generateRectangles();drawRectangles(rectangles);
<canvas id="canvas" width="500" height="500"></canvas>

Choose random color pallet from the list on page load

Updated answer after clarification (picking a random colour set):

$(document).ready(function() {  var palettes = [    ['red', 'blue', 'green'],    ['yellow', 'cyan', 'orange'],    ['cyan', 'orange', 'blue']  ];  var randomPalette = palettes[Math.floor(Math.random() * palettes.length)];    var new_bgcolor = randomPalette[0];  var new_textcolor = randomPalette[1];  var new_bordercolor = randomPalette[2];
$('#color-div').css({ 'background-color': new_bgcolor, 'color': new_textcolor, 'border-color': new_bordercolor });});
#color-div {  border: 1px solid gray;  width: 50px;  height: 50px;  text-align: center;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div id="container">  <div id="color-div">    test  </div></div>

How to generate random pastel (or brighter) color in Javascript?

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 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);
}

Generating a random color for the left border of multiple div elements

You have tagged this question with jquery, but appear to be using mostly pure javascript. I've provided a jquery solution below (which is a bit shorter code wise) but also a working javascript solution if you need it. At the moment you're combining jquery selectors and styling commands with javascript selected elements (which won't work!).


JQuery Solution

The code below acts as you would like, it uses jquery to iterate over each of the divs with class .content-box and assign a random colour using your generator. It is a little simpler than the pure javascript code version below.

// Set initial colourssetRandomBorderColor();

// Change colours if button clicked$("#changeColor").click(function() { setRandomBorderColorPureJS();});

// Assign random colours to all .content-box elementsfunction setRandomBorderColor() {
$(".content-box").each(function() {
$(this).css("border-left-color", getRandomColor());
});
};

// Generate random colourfunction getRandomColor() { var letters = '0123456789ABCDEF'; var color = '#'; for (var i = 0; i < 6; i++) { color += letters[Math.floor(Math.random() * 16)]; } return color;}
.content-box {  border: 5px solid black;  margin: 5px;  padding: 5px;  min-height: 30px;  min-width: 30px;  float: left;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="changeColor">Change Colours</button>
<div> <div class="content-box"></div> <div class="content-box"></div> <div class="content-box"></div> <div class="content-box"></div> <div class="content-box"></div></div>

Generate random colors for each box individually all at the same time using JQuery, HTML, and CSS

This is what you want:

var myColors = ['red', 'purple', '#E84751', 'blue', 'orange', '#323643', '#97FF73', '#362EFF', '#FF6513'];
function clickMe() {
$(".square").each(function() {
var randomize = Math.floor(Math.random() * myColors.length);
$(this).css("background-color", myColors[randomize]);
});
}

function cloneMe() {
$(document).ready(function() {
$(".square:first").clone().attr('class', 'square').appendTo('.orange-square-container');
clickMe();
});
}

Inside your clickMe function you forgot to change $("#square") to $(".square") i've moved the randomize into the .each function.

Demo

var myColors = ['red', 'purple', '#E84751', 'blue', 'orange', '#323643', '#97FF73', '#362EFF', '#FF6513'];
function clickMe() { $(".square").each(function() { var randomize = Math.floor(Math.random() * myColors.length); $(this).css("background-color", myColors[randomize]); });
}
function cloneMe() { $(document).ready(function() {
// var i = 1; // while(i <= 5) { $(".square:first").clone().attr('class', 'square').appendTo('.orange-square-container'); clickMe(); // i++;
});}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div class="btn-alt-container">  <a class="btn btn1-alt" onclick='clickMe()'>Push Me</a>  <div class="btn btn2-alt" onclick='cloneMe()'>Make More</div></div>
<div class="container"></div>
<div class="orange-square-container"> <div class="square"> <div class="content"> Hack Reactor's Awesome :) </div> </div></div>


Related Topics



Leave a reply



Submit