Categories:

Applying border & opacity to images onMouseover in CSS

In this tutorial, I'll show you how to use CSS alone to reproduce two popular image effects that have traditionally been done using scripting. The advantage of looking to CSS instead is obvious- much more lightweight and easier to implement. The two effects in question are:

border onMouseover

  opacity onMouseover

For cross browser compatibility (IE5+, FF1+), the image needs to be hyperlinked in order for the CSS to work, as IE (as of IE6) only supports the ":hover" pseudo class on A elements. Lets now look at the CSS code for each of the two effects separately.

Applying border onMouseover to images

First up, the CSS technique for applying a border to image links onMouseover:

<style type="text/css">

.borderit img{
border: 1px solid #ccc;
}

.borderit:hover img{
border: 1px solid navy;
}


</style>

<a href="http://cnn.com" class="borderit"><img border="0" src="email.gif" /></a>

By using the CSS pseudo class ":hover", we apply the enclosed CSS definitions to only when the mouse moves over any image with class="borderit".

Applying opacity onMouseover to images

Moving on, here's the CSS code for manipulating an image's opacity onMouseover:

<style type="text/css">

.opacityit img{
filter:progid:DXImageTransform.Microsoft.Alpha(opacity=40);
-moz-opacity: 0.4;
opacity: 0.4;
}

.opacityit:hover img{
filter:progid:DXImageTransform.Microsoft.Alpha(opacity=100);
-moz-opacity: 1;
opacity: 1;
}

</style>

<a href="http://cnn.com" class="opacityit"><img border="0" src="email.gif" /></a>

Note the three different properties used to specify opacity in CSS: In IE6 and below, the "filter" property is used (range: 0-100), and in older versions of Firefox, "-moz-opacity" (range: 0-1). Finally, for modern browsers, we just use the standard "opacity" property.