Dominant color of image as background of DIV, all in CSS

I was trying to do something fancy, and have a grayscale image turned into colored mode on mouse hover, together with showing a popup… and I obviously wanted the popup background color to be related to the image that had just been coloured up.

There is a precise javascript function that does that, it’s the color thief plugin for jQuery. Other than needing javascript to achieve the result (which may be fine), it wasn’t viable in my situation because it cannot work cross-domain with images stored on a different website from the one calling the javascript.

My original idea was to have it all done in CSS anyway, so a bright idea popped into my mind: why not using the browser itself to find the dominant color? And when does the browser find the dominant color of an image? When you resize it to 1pixel x 1pixel.

So…

background-image:url(yourimage);
background-size: 1px 1px;

that’s all for the basics.

If you want to make the colour stand out more, but only in non Internet Explorer browsers (thank you Microsoft) then to those declarations you can add:

-webkit-filter: saturate(5);
filter: saturate(5);

You obviously have to insert this code in the relevant place of your page… be it with hardcoded values (but if they were, wou wouldn’t be here asking how to DINAMICALLY find the dominant colour of an image) or with PHP or anything else in the backend directly inside a style="..." CSS statement inside the HTML tag.

The background colour may be too dark for black text, or too bright for white text depending on the image, so unless you want to apply an ugly text-shadow all around the characters to make them always readable (not so much actually, unless you’re using huge fonts), you may want to have a container DIV with a couple of DIVs inside, one holding the background, with half opacity, and the other containing the text, both with 100% width and height, and absolutely positioned to top:0;left:0; inside the container, maybe with a z-index:-1; on the background div.