CSS Image Transparency

lør, feb 13, 2010

Engelske guides

Learn how to change image transparency (opacity) using only CSS code. Simple but useful technique that you can use to create nice looking gallery or just crossover effect.

Here is how it looks like…

Changing image opacity (transparency) using css :
DC logo DC logo DC logo

Image opacity wih different crossover effect (move your cursor over it) :
DC logo DC Logo

So let’s get started. First create a new HTML document (index.html), create folder “style” and inside it create our CSS file (style.css).

Our basic HTML file looks like this :

<html>
<head>
	<title>CSS Image Transparency | Designers-Chair.com</title>
	<link href="style/style.css" rel="stylesheet" type="text/css">
</head>
<body>

</body>
</html>

Tag title defines page name :

<title>CSS Image Transparency | Designers-Chair.com</title>

This is the path to our external CSS file :

<link href="style/style.css" rel="stylesheet" type="text/css">

Body is empty so nothing will be displayed when we open our HTML file in web browser. Now we are going to display our picture.

...
<body>
<img src="DClogo.jpg" width="145" height="115" alt="DC Logo"/>
</body>
...

Now we see the picture but there is no transparency. Open style.css and add the following code :

img
{
	opacity:0.5;
	filter:alpha(opacity=50);
}

Notice how we have two same properties for img tag. This is because Internet Explorer uses filter:alpha(opacity:x) function (x = 0-100), but Firefox and Crome use opacity:x (x = 0-1). 0 = invisible, 1/100 = 100% visible.

Crossover effect is now easy to do. We just need to add onmouseover and onmouseout.

...
<img src="DClogo.jpg" width="145" height="115" alt="DC Logo"
onmouseover="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseout="this.style.opacity=0.5;this.filters.alpha.opacity=50" />
...

You can also use hover function (instead of onmouseover, onmouseout) , just add it to style.css. Note that this technique does not work with IE 6 (:hover is supported only on <a> elements).

img
{
	opacity:0.5;               /*Firefox & Chrome*/
	filter:alpha(opacity=50);   /* IE */

}

img:hover
{
	opacity:1;               /*Firefox & Chrome*/
	filter:alpha(opacity=100);   /* IE */
}

That’s it! Simple but very useful and attractive.

Tags: , , , , , , , , , , , , , , , , ,

Related posts

, , , , , , , , , , , , , , , , ,

Comments are closed.