bertdesign.de
music, webdesign, stuff-

The problem:
I want to add a hover effect to some images. These images aren’t background images, they are images of different people. Anyway, I’d like to use the idea of css sprites. Here, I want to “translate” this technique for using regular images instead of background-images. The reason to do this is simple: I don’t need one picture for layout reasons, I need many pictures to behave in the same way — changing color & border in a certain way. By the way, the images will be links, too
So let’s get started:
The HTML code:
<div> <a href="#"> <img title="”Mr. X" src="”the_image.jpg" alt="”Mr. X" /> </a> </div>
There are three main elements included:
- A div with the class “member”
- The link
- The image itself
As you can see, the link contains the image, the div contains these two. The image already contains the states I need: On the left side a b/w-picture with a green border, on the right side the colored one with a yellow square added.
Pretty boring without CSS if you ask me. Let’s move on to the CSS-part:
Attention: The different px values are matching the pixel size of the image, as commented in the CSS file. You have to fit these to your needs.
div.member { width: 210px; /* 50% of image width */ height: 200px; /* image height */ overflow: hidden; } div.member a { text-decoration: none; display: block; width: 420px; /* 100% image width */ } div.member a img { border: 0; } div.member a:hover { margin-left: -210px; /* as above, 50% of image width. Watch out: negative value! */ }At first, the surrounding div gets a fixed width, which is exactly 50% of the images width. The height matches the image height.
Setting “overflow: hidden;” causes only the left side of the image to appear.
Now, the link-element is styled. “text-decoration: none;” prevents the underline (as you might know…). Far more important is the next step: The link element turns into a block-element with “display: block;”. Now you can add a fixed width to this element. As you see, the width is exactly the image width.
To prevent little pixel errors, the img element gets rid of the border with “border: 0;”.
Finally, the real “action” is done with editing the a:hover state.
Simply add a negative left margin to the picture. This margin again matches 50% of the images width. In this way, the image gets pushed to the left, revealing the colored right side.
Result:
- minimal usage of CSS & extra markup
- nice hover effect
- should work in most browsers (please comment if you find errors!)
Any comment on this technique is appreciated. If you like this tutorial, let me know!
(There might be tutorials about this technique in other places. I couldn’t find any in a quick google search
This should at least work with FireFox and Safari on a Mac, that’s what I was able to test. IE seems to work too, according to some friends testing it.)Ähnliche Artikel

Mag ich! (1)

Frisch diskutiert: