Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS pick a random color from array

Tags:

Is there is a way in CSS to make it pick a random font color from an array? I know I can do this with server side or javascript, but I am wondering if there is pure CSS way to do this.

like image 507
Saqib Ali Avatar asked Feb 20 '13 16:02

Saqib Ali


People also ask

Which function we use to pick a random color item from an array or number?

backgroundColor = 'rgb('+ rgb. join(',') +')'; If you want to constrict it to known colors, you can create an array of the colors and randomly select it like so.

How do I change the random background color in CSS?

setProperty('--main-bg-color', randomColor); Note that you can also create CSS variables for specific elements, not just the root document element. Or you could use a completely different way of selecting a random color (like user input). This allows for possibilities like theming.


2 Answers

CSS expressions (allowing for dynamic script content via CSS) were abominations cast in the bowels of the hell of inefficiency alongside Web Forms, only ever supported by IE7 and below. But since you asked.

<style> blink marquee {    color: expression("rgb(" + Math.floor(Math.random() * 255)       + "," + Math.floor(Math.random() * 255) + ","       + Math.floor(Math.random() * 255) + ")"); } </style> <blink>    <marquee>       color me beautiful    </marquee> </blink> 
like image 139
Explosion Pills Avatar answered Sep 28 '22 09:09

Explosion Pills


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); 
like image 45
bdesham Avatar answered Sep 28 '22 08:09

bdesham