May 16, 2012

Rollover Images Using CSS

    How about images that changes its appearance whenever your viewers hover their mouse on them. How would this be useful to your blog? Well, instead of having the regular buttons for navigation, social widgets and a lot of other stuffs, you can have a stylish rollover image link instead. Here are some samples below, try to place your cursor over them.





    Now let us see how the magic works. Below are the original images that you are seeing from the samples above. Using CSS, we set the images as backgrounds of divs. Then the CSS code for the hover state would change the background position of the div causing the div's background to display the lower part of the image.

Rollover Image Sample 1 Rollover Image Sample 2 Rollover Image Sample 3

    In this sample, the divs height and width is 64x64 which would be exactly fit to display only one side of the image, and then we modify the position of the divs background by setting the background-position of the div to 0px -64px, wherein the values would be the x and the y of the background's position. The value of the y would be determined by the height of your image - which would be half the height of your image and in a negative value.

    This is the best rollover approach for images since the browser won't need to load another image once the element is in a hover state. Now let us see the code for these rollover images.

Show or Hide Code for Rollover Sample 1
Show or Hide Code for Rollover Sample 2
Show or Hide Code for Rollover Sample 3

    If you merge the images horizontally, you would need to change the x and y value, wherein the x would have the value now instead of y. For instance in this sample, it would be background-position: -64px 0px; See the sample below.

Show or Hide Code for Rollover Sample 4

Arrow Alternate rollover wherein x position is modified instead.

No comments:

Post a Comment