简体   繁体   中英

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>

You are changing the background of the image. Unless you are changing its opacity to 0 you won't see the background.

I suggest to remove the image and give the a-tag your class. In addition specify the image-src as normal background.

.class1{
display:block;
background-image:url(...);
...}
.class:hover{...}

and your link <a href="http://mylink" class="class1">&nbsp;</a>

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');
 }

don't forget to add the properties below (to the class/tag/div containing the background-image property). Otherwise, it will repeat in some cases:

{
  background-size: contain;
  background-repeat: no-repeat
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM