Color Animate Any Shape with a Knockout PNG

Published by Chris Coyier

You normally don't think of <img> as having a background color, but they certain can have that property. It might come up if say, you wanted two borders around your images. You could use border for one and simulate the other by giving the image a background-color and padding. Or maybe you set the background to a bright red color so that missing images are bold and obvious.

There is another reason you might want to declare a background color on an image, and that's to show the color through the transparent parts of the image. In fact, with that idea, you can create any shape you want as a "knockout" and set the color behind it. That means you can control the color of that unique shape through CSS and do any of the neat stuff CSS can do. Like say, animate it's color!

First we make an image where the solid parts match the solid color of the background of the site we are working with. For sake of example, white. The "shape" is the transparent part. Here's what that would look like in Photoshop:

We put it in the markup:

<img src="images/marilyn.png" alt="">

And we color it:

img { background: red; }

Then we make an animation to cycle through some colors. Two syntaxes for this now (grunt):

@-webkit-keyframes super-rainbow {
    0%   { background: red; } 
    20%  { background: orange; }
    40%  { background: yellow; }
    60%  { background: green; }
    80%  { background: blue; }
    100% { background: violet; }
}

@-moz-keyframes super-rainbow {
    0%   { background: red; } 
    20%  { background: orange; }
    40%  { background: yellow; }
    60%  { background: green; }
    80%  { background: blue; }
    100% { background: violet; }
}

Then we apply that animation to the image:

img {
     background: red;  
     -webkit-animation: super-rainbow 15s infinite alternate linear; 
     -moz-animation: super-rainbow 15s infinite alternate linear; 
}

That'll do 'er. Check out the demo for this example and other quick fun one of rainbow gradient on a bicycle shape that moves on hover.

View Demo   Download Files

Images snagged off of Vecteezy.