Search code examples
csstransparencyopacity

Can I do knock-out/punch-through transparency with CSS fonts?


I would like to know if there is any way I can apply 100% transparency to text so that we can see the background picture of the page within the characters in the text.

i.e. imagine I’ve got a <div> with a white background, and a background image on <body>. I’d like to set the text inside the <div> so that the background image on <body> can be seen through the text, despite the white background on the <div>.

I could probably use an inverted font but I would prefer a better way to do it if there is one.


Solution

  • Does it have to be dynamic? The only way to do that is with an image with transparency (GIF or, better, PNG).

    I'm not sure if this is what you want, but will explain it anyway.

    Situation: you have a non plain background that you want to bee seen through your text.

    Solution: no CSS is coming to the rescue for this. You'll have to use your trusty image editor to create a layer with text, and another layer that will be the negative of your text

    This could allow you to have some interesting effects, but if you want it to be dynamic, you'll have to generate the images on the fly serverside.

    This kind of trickery is currently impossible with pure CSS (might be possible with Javascript).


    Edit

    Seeing Paul's find on webkit got me thinking on how to fake that behavior in Firefox, Opera and IE. So far I've had good luck using the canvas element on Firefox, and I'm trying to find some behavior in filter:progid:DXImageTransform.Microsoft.

    So far with canvas, this is what I did

    <html>
    <body>
    <canvas id="c" width="150" height="150">
    </canvas>
    <script>
    ctx = document.getElementById("c").getContext("2d");
    // draw rectangle filling the canvas element
    ctx.fillStyle = "red";
    ctx.fillRect(0,0,150,150);
    
    // set composite property
    ctx.globalCompositeOperation = 'destination-out'; 
    // the text to be added now will "crop out" the red rectangle
    ctx.strokeText("Cropping the", 10, 20);  
    ctx.strokeText("red rectangle", 10, 40);  
    
    </script>
    </body>
    </html>
    

    by using a detination-out compositing and drawing text on the canvas.