Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random color with pure CSS (no javascript)?

Tags:

css

random

colors

Is it possible to generate random color with pure CSS and without using javascript? It's probably impossible but I'm still curious.

like image 737
Arch1tect Avatar asked Mar 10 '13 21:03

Arch1tect


People also ask

How do I generate a random color in CSS?

var randomColor = Math. floor(Math. random()*16777215).


2 Answers

This isn't really possible in pure CSS.

However, using a pre-processor like SASS (example) or LESS (example) can generate random colors for you because they are built using scripting languages. Keep in mind that this value is then not random for each user or visit, unless the CSS file is generated for each user or visit individually (which is less common).


One side note is the possibility for using CSS variables. We can declare a CSS variable by saying:

html {   --main-bg-color: brown; } 

and use it like so:

html {   background-color: var(--main-bg-color); } 

Now we can change it using JS:

// From http://stackoverflow.com/a/5365036/2065702 const randomColor = "#"+((1<<24)*Math.random()|0).toString(16);   document.documentElement.style.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.

like image 105
Zach Saucier Avatar answered Sep 29 '22 00:09

Zach Saucier


I found for you something here, but it uses PHP. I think it's impossible with plain CSS.

like image 39
Iwo Kucharski Avatar answered Sep 29 '22 01:09

Iwo Kucharski