Using only CSS, can I use only the PNG alpha channel?

I have this red PNG image that has variable transparency, but I need to display it on the web page as white with variable transparency. I think this can only be two ways:

  • Set the background color to white, but somehow use the PNG alpha channel to set its transparency.
  • Somehow, de-saturate PNG or change your color palette to white only.

I am only allowed to use CSS to achieve this; otherwise, I would consider other options.

Change I only need this to work in Safari (webkit). Sorry, I haven't mentioned this before.

+4
source share
3 answers

Requested Answer:

-webkit-mask you can take an image and use its alpha channel as a mask (pretty much like a mask for Photoshop)

 div { background:white; -webkit-mask:url(url/to/image.png); } 

Fiddle

But I agree with all the answers suggesting canvas - I know you're limited to pure css, but canvas is the way to go here.

+6
source

No, you cannot do this in a cross browser using only CSS.

(It would be pretty easy to do this using an HTML5 canvas along with your image.)

Canvas Solution :

You can view this example here: http://phrogz.net/tmp/canvas_png_alpha.html

 var ctx = document.createElement('canvas').getContext('2d'); var img = new Image; img.onload = function(){ // Make the canvas the same size as the image var w = ctx.canvas.width = img.width; var h = ctx.canvas.height = img.height; // Fill it with (fully-opaque) white ctx.fillStyle = '#fff'; ctx.fillRect(0,0,w,h); // Draw the image in a special blend mode that forces its opacity on the result ctx.globalCompositeOperation = 'destination-in'; ctx.drawImage(img,0,0); // Set an image on the page to use this canvas data // The data URI can also be copy/pasted and used inline in HTML or CSS document.getElementById('result').src=ctx.canvas.toDataURL(); } // Load the image to use _after_ setting the onload handler img.src = 'alphaball.png'; 

source image whose alpha is used:
A round ball with a couple holes and transparent shadow
Result (shown on black page):
white silhouette on black background

The key here is used in destination-in layout mode to use the opacity of the original image as a result, leaving the original color (in this case white) intact.

+5
source

In versions of IE less than 9, there is a color filter that does this. In other browsers you are out of luck.

You can use the canvas tag with some javascript to get the same effect, but this is not CSS.

+3
source

All Articles