Change Image Opacity Easily Using CSS or JS

by Hiroshi on January 23, 2009

in CSS, Javascript, Tricks

We can simply use CSS alone to reproduce opacity effect that have traditionally been done using scripting. The advantage of looking to CSS instead is obvious – much more lightweight and easier to implement. We can use this method where we need to use a dim or faint version of image, while when some one places mouse over it, then image comes sharp, clear and bright.

Use the following code in head section of web page.

<style type="text/css">
.opacityit img{
-moz-opacity: 0.4;
.opacityit:hover img{
-moz-opacity: 1;

Use the following code in body where the image is located.

<a href="#" class="opacityit"><img border="0" src="email.gif" /></a>

By this method image loads kind of blur in background and in light colors, but when some one places mouse over it. It becomes sharp.

Simple Opacity

We are using JavaScript to change the opacity of an image here. The technique works in both IE4+ and NS6+, and can be used to create some interesting “fading” effects. Here is the simple way to just place an image with opacity.

<img src="image.gif" style="filter:alpha(opacity=50); -moz-opacity:0.5">

In -moz-opacity:0.5 accepted range of values are 0 to 1, where 0 would make the image disappear and in alpha(opacity=50) range is between 1 to 100. We have combined the code both for IE and Mozilla for code compatibility.

We can also alter the opacity of image using javascript.

Head section code

function alteropacity(imageobject, opacity){
 if (navigator.appName.indexOf("Netscape")!=-1
 else if (navigator.appName.indexOf("Microsoft")!= -1 

Body Section Code

<img src="image.gif" style="filter:alpha(opacity=50); -moz-opacity:0.5" 
onMouseover="alteropacity(this, 100)" onMouseout="alteropacity(this, 30)">

Related Posts

Previous post:

Next post: