alter image on mouseover with CSS

How to change image on hover using CSS? Here we give you two methods:

using two images

<html>
<head>
<title>test</title>
<style>
.altericon1{width:130px; display:block; height:33px; line-height:33px; overflow:hidden; background-image:url(icon1.jpg); background-repeat:no-repeat; }
.altericon2{width:130px; display:block; height:33px; line-height:33px; overflow:hidden; background-image:url(icon2.jpg); background-repeat:no-repeat; }
</style>
</head>
<body>
<a href="" class="altericon1" OnMouseOver = "this.className='altericon1'" OnMouseOut = "this.className='altericon2' "></a>
</body>
</html>

In this example, the anchor’s class is altered on the event of mouseover and mouseout. When mouse hovers over the anchor, the anchor has the class of altericon1 which takes icon1.jpg as the background. When mouse moves out the anchor, it changes the class to altericon2 which takes icon2.jpg as the background. Now when you move mouse on and off the anchor, you will see different background images. This method requires two different images, which is a little inconvenient.

Using single image

<html>
<head>
<title>test</title>
<style>
.altericon{width:130px; display:block; height:33px; line-height:33px; overflow:hidden; background-image:url(altericon.jpg); background-repeat:no-repeat; background-position:left top;}
.altericon:hover{background-position:left -34px;}
</style>
</head>
<body>
<a href="" class="altericon"></a>
</body>
</html>

This method uses only one image. Note that the size of the image (altericon.jpg) is 130*66, which is double higher than the anchor so only half  image is displayed on the anchor(as the background). The class of the anchor is not changed anyway. But it uses a pseudo-class:.altericon:hover, which alters the position of the background image(relative to the top-left corner of the anchor) on hover using the CSS property background-position. The background image has two different parts: the top part is the same as icon1.jpg in previous example, while the bottom part is the same as icon2.jpg in that example. Without mouse hovering, background-position is set to “left top” which shows the top part of the image on the anchor. On mouse hover, background-position is set to “left, -34px”, which displays the bottom part of the background image on the anchor.

 

Comments are closed, but trackbacks and pingbacks are open.