3

I have 5 list items on my page, with the following CSS applied to them:

#content .gallery_work ul li {
    background-color: #FEF5D6 !important;
    border-right: 15px solid blue;
    color: #373C46;
    float: left;
    font-size: 13px;
    height: 250px !important;
    margin: 10px !important;
    text-align: center;
    width: 225px !important;
}

what I'd like to have is 5 possible border colors, and for each li to get one of the colors randomly applied to it.

Does anyone know how this can be done?

TylerH
  • 20,799
  • 66
  • 75
  • 101
dvent
  • 105
  • 1
  • 6
  • 17

2 Answers2

6

Just generate a number in JavaScript or your server side language of choice.

You could do it in JavaScript...

var color = "#" + Math.floor(Math.random() * 0xFFFFFF).toString(16);

...or PHP...

$color = "#" . dechex(rand(0, 0xFFFFFF));

Your comment...

Instead of using completely random colors, is there a way I could declare a number and then have it randomly choose from them?

Yes, for example...

$colors = array("#000", "#fff");

$randomColor = $colors[array_rand($colors)];
alex
  • 479,566
  • 201
  • 878
  • 984
  • 1
    I'm not sure if the OP wants to use JS (or server side), but the solution is very elegant.. +1 – Zoltan Toth Nov 18 '12 at 23:28
  • My site uses PHP so could use the second option. Instead of using completely random colors, is there a way I could declare a number and then have it randomly choose from them? – dvent Nov 19 '12 at 00:07
  • @DaveHunter Yes, set up an array of colours, and use `array_rand()` to choose a random key. – alex Nov 19 '12 at 00:12
  • @ZoltanToth Would you suggest something other than JS or a server-side language? – Jules Nov 19 '12 at 00:21
  • Please could you provide a little more detail on using this - I am a relative beginner with anything over simple CSS – dvent Nov 19 '12 at 00:21
  • So with the updated PHP you've added, where do I put this on my page (i.e. header, body etc.) and do i need any more info to make it happen on page load? Finally, how do I limit it to a div or element with a particular class? – dvent Nov 19 '12 at 00:41
  • @DaveHunter If you're asking that, you're probably better reading a few PHP tutorials first. – alex Nov 19 '12 at 00:45
  • If anyone is willing to provide some advice, it'd be appreciated! – dvent Nov 19 '12 at 01:07
1

A solution that covers all edge cases, as in add proper zero padding:

function randomColor() {
    return (function(h) {
         return '#000000'.substr(0, 7 - h.length) + h;
    })((~~(Math.random() * (1 << 24))).toString(16));
}

Originally by Remy Sharp: http://paulirish.com/2009/random-hex-color-code-snippets/#comment-34878

david
  • 471
  • 4
  • 13