Search code examples
htmlcsshoverscale

Resizing a background-image using pure css inside a class:hover


I have a image, and i want it to change to another one when the mouse passes by. It seems correct to me, but it always appear big, in its normal size (128px x 128px), and BEHIND the another image. (the other one is inside a div with z-index:1), and the one with the mouseover img have z-index:999

here is my css

.class1{
    max-width:64px;
    max-height:64px;
}
.class1:hover{
    background-image:url(http://img195.imageshack.us/MOUSEOVER_IMAGE.png);
    width:64px;
    height:64px;
    z-index:999;
    background-position:top center;

and here is my image

<a href="http://mylink"><img class=class1 src="http://imageshack.us/NORMAL_IMAGE.png" alt="some text here" /></a>

Solution

  • There are a couple issues going on here. Like Tobas mentioned, you're using a background image on the link, but you still have an image child element. z-index will not bring a parent element's background above a child element.

    So you have a couple options:

    1: Change the img opacity to 0 on hover:

    img.class1:hover { opacity: 0 }
    

    And use background-size on the background image:

    a:hover {
      background: url(...);
      background-size: 64px 64px;
     }
    

    2: Remove the child image entirely, and have the images be swapped out as backgrounds to the link. This makes sense if the image presents no semantic value.

    a { background: url(image1.png); }
    
     a:hover { background: url(image2.png); }
    

    3: Swap the image itself with javascript/jquery:

     $('img.class1').hover(function(){
        $(this).attr('src','image2.png');
     }