Skip to content Skip to sidebar Skip to footer

Switch Between Two Images In Html With Css

I'm working on a wordpress theme and want to switch between two thumbnail images on hover. The code that i have looks something like this :

Solution 1:

Solution 2:

First, you want to get rid of the img tags and use only css:

a:link {
background: url("img1.jpg");
}
a:hover {
background: url("img2.jpg");
}

You could use javascript but that would get very complicated, CSS3 however will have fade effects ready soon:

a:link {
background: url("img1.jpg");
-webkit-transition:background 1s ease-in;  
-moz-transition:background 1s ease-in;  
-o-transition:background 1s ease-in;  
transition:background 1s ease-in;  
}
a:hover {
background: url("img2.jpg");
}

Solution 3:

You don't need the two <img> tags in there, you just have to reference the images and hover state in CSS:

a.thumb
{ 
   background-image: url(img1.jpg);
}

a.thumb:hover 
{ 
   background-image: url(img2.jpg);
}

The most basic of hover examples.

You can also use CSS sprites:

a.thumb
{ 
   background-image: url(img1_sprite.jpg);
   background-position: 00;
}

a.thumb:hover 
{ 
   background-image: url(img1_sprite.jpg);
   background-position: -60px0; /*see below*/
}

This shoves the background to the left where 60px is the width of your second image.

For fading images you can use CSS3 transtitions, but IE does not support this until Version 9.

Post a Comment for "Switch Between Two Images In Html With Css"