Log in Sign Up

Masking an Image with a Transparent PNG

So the pictures on your site are boring, and you want to spruce them up a bit? Want to frame your pictures in a seasonal theme without having to edit them all? Here's a quick and easy way to mask images using a transparent PNG and a little HTML and CSS. The mask is applied using CSS alone, so you can style the mask just like you style any of the other stuff on your site.

I've created a quick demo of how it works here, so feel free to surf over there and check out the functionality and the source code.

The HTML

The HTML is comprised of a wrapper, the image, and the mask. Then we'll use a little CSS to fix up the positions and apply the mask image.

<div class="imageWrap">
  <img src="images/picture_sample.jpg" />
  <div class="cssMask"></div>
</div>

If you are running on MagicEdit, you can make the image editable just by adding the magicedit attribute and (optionally) an me_name to the image:

  <img magicedit me_name="maskedImage" src="images/picture_sample.jpg" />

The CSS

In order for this technique to work, the mask needs to be positioned absolutely over the image, so two things need to happen. The image needs to be contained in a wrapper with position:relative, and the mask needs to have position:absolute. This allows the mask image to be positioned absolutely relative to the image wrapper. Note that I'm placing the mask DIV after the image so that it naturally will sit on top when absolutely positioned. This way we avoid any nasty z-index issues with IE.

.imageWrap {
  position:relative;
}

.cssMask {
  width:255px;
  height:306px;
  position:absolute;
  top:0;
  left:0;
  background:url(images/Picture_frame_WhiteBkg.png) 0 0 no-repeat;}
}

Make sure the path to the mask image is correct, and that the width and height of the mask image and mask container all match the dimensions of the image you are masking.

The one drawback to this technique is that IE 6 does not support transparent PNGs. There is a JavaScript fix for that, so see the demo page for more details.

Conclusion

Now you can spruce up your images with a nice frame that can be quickly updated just by changing the mask file on your site. Don't forget to try out the demo with your own pictures!

Try MagicEdit today!

Sign Up for free Demo
Scroll to Top