Search code examples
cssfiltercolorspng

CSS - Add Color to Black & White PNG Image Using a Filter


Is it possible in CSS to add color to a black & white image using a filter? I'm talking about using filters like it's possible in Photoshop, and an even better example would be the ones in Microsoft PowerPoint.

What I'm trying to do is this: I have an image file of a black icon. I want to add a filter to it such that everything in the image (the background is transparent) will have the color I choose by using the filter, such that I'd be able to have the icon in whatever color I want. Like I said in the title, it's a PNG image, so as far as I know, I can't use SVG filters.

How can I do this? I'm trying to write a theme for a website using the original icons, and I'm stuck on this.

Update: I want to use the original PNG images. I'm not going to replace them with SVGs, or pre-edited PNGs.

Thanks a lot in advance!


Solution

  • You can do it with CSS filters, though I wouldn’t recommend that at all:

    .colorizable {
        filter:
            /* for demonstration purposes; originals not entirely black */
            contrast(1000%)
            /* black to white */
            invert(100%)
            /* white to off-white */
            sepia(100%)
            /* off-white to yellow */
            saturate(10000%)
            /* do whatever you want with yellow */
            hue-rotate(90deg);
    }
    
    .example-clip {
        display: block;
        height: 20px;
        margin: 1em;
        object-fit: none;
        object-position: 0 0;
        width: 300px;
    }
    
    .original {
        filter: contrast(1000%);
    }
    
    body {
        background: #333;
    }
    <img class="colorizable example-clip" src="https://cdn.sstatic.net/Sites/stackoverflow/img/wmd-buttons.svg" />
    <img class="original example-clip" src="https://cdn.sstatic.net/Sites/stackoverflow/img/wmd-buttons.svg" />