How to Use Transparent Images with CSS3

By Nathan Segal

In this article we're going to look at what you can do with the new opacity property in CSS3. We're going to use it in three forms: As a transparent image, a hover effect and as text on a transparent (and layered) background.

Before we get into the CSS here, I want to briefly go over the uses of images. For this tutorial I used Corel PHOTO-PAINT X5 and saved all images using the JPEG format. While you can use PNG I recommend avoiding that because it will bloat your file sizes by 5-10x.

It's important to consider is how the images will be used. If you need high quality, a setting of 8 will do the trick.. If the image is for a background and it's not necessary that the image be really aharp, you could use a lower compression setting. This will create a smaller file size and will allow the image to load faster.

Another option is to use textured images for the background, which can reduce the file size by quite a bit. In this case, depending on the quality you want, you could make use of either JPEG or GIF. GIF files tend to be considerably smaller and they load faster as a result. This is also where you can use another form of PNG, PNG-8, which will give you 256 colors.

While the size of images isn't as much of a concern now as it was years ago when dial-up was more common, it's still a good practice to keep your file sizes down whenever possible since this will reduce page loading times.  If your pages take too long to load you run the risk of losing your audience.



The Uses of Opacity

If you have several images with varying degrees of opacity, you can style the CSS with the appropriate tags (if you're creating multiple pages with the same effect) or if it's just for one page, you might want to add CSS styling to the appropriate images. Here's what the code would look like as applied to a single image:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style>
  #img {
  opacity:0.4;
  }
</style>
</head>

<body>
<div id="img">
<p><img src="butterfly.jpg" width="300" height="231" alt="butterfly in saanich" /></p>
<p><img src="butterfly.jpg" width="300" height="231" alt="butterfly in saanich" /></p>
<p><img src="butterfly.jpg" width="300" height="231" alt="butterfly in saanich" /></p>
<p><img src="butterfly.jpg" width="300" height="231" alt="butterfly in saanich" /></p>
</div>
</body>
</html>

And here's the result in the browser.

With different opacities applied to different images, here's the code:

<p><img src="butterfly.jpg" width="300" height="231" alt="butterfly in saanich" /></p>
<p><img style="opacity:0.5;" src="butterfly.jpg" width="300" height="231" alt="butterfly in saanich" /></p>
<p><img style="opacity:0.3;" src="coho.jpg" width="300" height="224" alt="coho ferry" /></p>
<p><img style="opacity:0.9;" src="henry.jpg" width="300" height="224" alt="henry the heron" /></p>