Michael-Li.com

Michael Li Picture
See my vision and experience my life as a young entrepreneur wtih ambition to learn and experience this wonderful world.
M.Li

Image Swap Using CSS

Filed in: Web Design,Web Development

When I was designing the new Ask-a-Pro Detailer blog for Detailed Image I figured out a way to do an image swap without using Javascript.

The basis of this image swap technique is to set a background image to be your image you want to have swapped when you hover over it. Then insert the default image which will sit on top of the background hiding the background. Create a style to change the opacity of the default image to full transparency when you hover over it, voila you have an image swap.

Requirements
CSS3 Property: Opacity
Opacity changes the transparency of an element. Most modern browsers already support this CSS3 property. Set values between 0.0 (full transparency) to 1.0 (no transparency).

CSS2 Property: Pseudo Class :hover
Pseudo Class :hover is a dynamic action that happens when you hover over an element.

Examples:

CSS image swap
Basic image swap using CSS.

The Code:
HTML
<div id=”css-image-swap-1″>
<img id=”swap-1″ src=”default-image-url” alt=”CSS image swap” />
</div>

CSS
#css-image-swap-1{
width:300px; height:150px; background:url(swap-image-url);
}
#css-image-swap-1 img:hover{
opacity:0;
}

This isn’t an image swap but it gives a very similar effect by changing the opacity of the image. Using this technique you could fade an image in and out of transparency.

The Code:
HTML
<div id=”css-image-swap-2″></div>

CSS
#css-image-swap-2{
width:300px;
height:150px;
background:url(image-url);
}
#css-image-swap-2:hover{
opacity:.5;
}

I mentioned above that this method should work with most the modern browsers but I know it doesn’t work for IE7 and older because IE totally sucks.

I’m sure this has been done before but I’d thought I’d share this with everyone. I didn’t find this particular technique when I searched for CSS image swap but I did find others using this basic concept using CSS visibility instead of CSS opacity. Both techniques will get the job done for an image swap.

02/14/2010 Comments (0)

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

    Flickr Image Link
    X