Change background color of div for each new div

I have a loop that creates a new div for each unique event

while($event!=$nextEvent){ echo'<div id='sportType'>'; //some code echo'</div>' } 

I would like to automatically change the background color to a different background color for each div created, each div should be a separate / unique color, there will never be more than 7 divs

Something like that

enter image description here

Any idea how I can do this?

+6
source share
3 answers

Since there are at most 7 divs, you can do this with a pure css and nth-child selector

 div:nth-child(1) { background: gray; } div:nth-child(2) { background: red; } div:nth-child(3) { background: cyan; } div:nth-child(4) { background: blue; } div:nth-child(5) { background: black; } div:nth-child(6) { background: green; } div:nth-child(7) { background: yellow; } 

If you want more than seven divs this will be more practical with javascript like

 var divs = document.getElementsByTagName('div'); for(var i =0; i < divs.length; i++){ divs[i].style.background = getRandomColor(); } function getRandomColor() { var letters = '0123456789ABCDEF'.split(''); var color = '#'; for (var i = 0; i < 6; i++ ) { color += letters[Math.floor(Math.random() * 16)]; } return color; } 
 <div>test</div> <div>test</div> <div>test</div> <div>test</div> <div>test</div> <div>test</div> <div>test</div> <div>test</div> <div>test</div> <div>test</div> 

Random color generator in JavaScript

+5
source

You can do it directly in PHP

Declare an array that contains color codes and use the array when creating the <div> dynamically. See the code below for an example.

 <?php $color= array("#341014", "#BE6353", "#2F2E3B","#20222B","#BB644C","#F8834E","#E4B9AC"); $i=0; while($event!=$nextEvent){ echo"<div id='sportType' style='background-color:".$color[i].";'>"; //some code echo'</div>'; $i++; } ?> 

You can simply specify any number of colors in the array, and it will apply colors accordingly, even if a large number of <div> , for example, for example, if you want to create 100 divs, you can simply add 100 or more than 100 color codes in your array, and these colors will be used in the while loop.

+2
source

you can use the rand function to generate new colors

 while($event!=$nextEvent){ $r=rand(0, 255); $g=rand(0, 255); $b=rand(0, 255); echo"<div id=\"sportType\" style=\"backgroung:rgb($r,$g,$b);\">"; //some code echo "</div>" } 

rand function will create a random number in the RGB color collection.

+1
source

Source: https://habr.com/ru/post/987333/


All Articles