2016-11-27 112 views
0

我在互联网上搜索,发现这个:How to display image over image on hover with css
我在jsfiddle和博客文章中使用Chrome和Firefox尝试了this image的代码。
没有一个显示结果,如this image
什么是不正确的我的代码?谢谢。'悬停图像显示图像'CSS无法正常工作

a { 
 
    position: relative; 
 
    display: inline-block; 
 
} 
 

 
a:hover:before { 
 
    content: ''; 
 
    display: block; 
 
    background-image:url('http://i.imgur.com/fGAbTOj.png'); 
 
    width: 50px; 
 
    height: 50px; 
 
    position: absolute; 
 
    top: 0; 
 
    left: 0; 
 
}
<a href="#"><img src="http://cdn.akamai.steamstatic.com/steam/apps/271590/ss_80b965d66b13d6eb5e1468151a371e12fe159663.600x338.jpg" /></a>

回答

0

使用background-size财产,因为你是设置background-image属性a:before元素和背景图像的大小为256x256。但是您已将a:before元素的width & height定义为50px,因此背景图片的大小也应为50px

只需使用:

a { 
 
    position: relative; 
 
    display: inline-block; 
 
} 
 

 
a:hover:before { 
 
    content: ''; 
 
    display: block; 
 
    background-image:url('http://i.imgur.com/fGAbTOj.png'); 
 
    width: 50px; 
 
    height: 50px; 
 
    background-size: 50px; 
 
    position: absolute; 
 
    top: 0; 
 
    left: 0; 
 
}
<a href="#"><img src="http://cdn.akamai.steamstatic.com/steam/apps/271590/ss_80b965d66b13d6eb5e1468151a371e12fe159663.600x338.jpg" /></a>

希望这有助于:

a:hover:before { 
    background-size: 50px; /* as you have 'width' and 'height' defined as 50px each */ 
} 

在下面的代码片段看看吧!

+0

谢谢,它只适用于'background-size'。但我仍然有一个问题,即为什么该图像的代码仍然工作,即使'background-size'丢失。 – Louis55

+0

@ ll55我的荣幸!但我仍然不明白,当'background-size'丢失的时候代码是在工作,也许我没有得到你的问题。 –

+0

“https://i.stack.imgur.com/zOjXI.png”中的代码可以在悬停图像时显示图像,即使是“background-size”丢失。 – Louis55