Use JavaScript.
You could either generate random colors or create an array of colors and pick a color sequentially or randomly.
var box = document.getElementsByClassName('box');
// An array we need to generate a random hex value.
var all = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']
// Function that will return a random element from the array 'all'
function rand() {
return all[Math.floor(Math.random() * all.length)];
}
// Loop through all '.box' elements
for (i = 0; i < box.length; i++) {
// Call the function 'rand()' six times to generate a valid hex value(#000000) and
// assign the new hex value to currently iterated '.box' element's 'backgroundColor'
box[i].style.backgroundColor="#" + rand() + rand() + rand() + rand() + rand() + rand();
}
.box{
position: relative;
display: inline-block;
width: 100px;
height: 100px;
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
To give specific colors to all .box
es you could put the colors in an array and use each color using the i
variable to pick the color sequentially.
var box = document.getElementsByClassName('box');
var colors = ['coral', 'blueviolet', 'burlywood', 'cornflowerblue', 'crimson', 'darkgoldenrod', 'olive', 'sienna', 'red', 'green', 'purple', 'black', 'orange', 'yellow', 'maroon', 'grey', 'lightblue', 'tomato', 'pink', 'maroon', 'cyan', 'magenta', 'blue', 'chocolate', 'darkslateblue', 'coral', 'blueviolet', 'burlywood', 'cornflowerblue', 'crimson', 'darkgoldenrod']
for (i = 0; i < box.length; i++) {
box[i].style.backgroundColor = colors[i];
}
.box{
position: relative;
display: inline-block;
width: 100px;
height: 100px;
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
4
solved how can i background-color 50+ divs with separate colors easily | CSS only [closed]