Is there any way to colorize a white PNG image with CSS only?

Balázs Varga picture Balázs Varga · Mar 26, 2015 · Viewed 57k times · Source

I know there are many css filters out there especially for webkit, but I can't find a solution for colorize a white (#FFFFFF) image. I've tried some combination of the filters, but none of them make my image colorized. I can only change the image in the range of grayscale, or sepia.

So my question is: Is there any way to change my totally white png to (for example) red using css only?

Like shown on this image:

enter image description here

Answer

James Montagne picture James Montagne · Mar 26, 2015

This can be done with css masking, though unfortunately browser support is really bad (I believe webkit only).

http://jsfiddle.net/uw1mu81k/1/

-webkit-mask-box-image: url(http://yourimagehere);

Because your image is all white, it is a perfect candidate for masking. The way the mask works is that wherever the image is white, the original element is shown as normal, where black (or transparent) the original element is not shown. Anything in the middle has some level of transparency.

EDIT:

You can also get this to work in FireFox with slight help from svg.

http://jsfiddle.net/uw1mu81k/4/

div {
  width: 50px;
  height: 50px;
  mask: url(#mymask);
  -webkit-mask-box-image: url(http://www.clker.com/cliparts/F/5/I/M/f/U/running-icon-white-on-transparent-background-md.png);
}
<div style="background-color: red;"></div>
<div style="background-color: blue;"></div>
<div style="background-color: green;"></div>
<div style="background-color: orange;"></div>
<div style="background-color: purple;"></div>

<svg height="0" width="0">
  <mask id="mymask">
    <image id="img" xlink:href="http://www.clker.com/cliparts/F/5/I/M/f/U/running-icon-white-on-transparent-background-md.png" x="0" y="0" height="50px" width="50px" />
  </mask>
</svg>