【问题标题】:'Hover image display image' CSS is not working properly'悬停图像显示图像' CSS 无法正常工作
【发布时间】:2017-04-11 02:19:57
【问题描述】:

我在网上搜索了一下,发现这个:How to display image over image on hover with css
我使用 Chrome 和 Firefox 在 jsfiddle 和博客文章中尝试了 this image 的代码。
他们都没有显示像this image这样的结果。
我的代码中有什么不正确的地方?谢谢。

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>

【问题讨论】:

    标签: html css image hover display


    【解决方案1】:

    使用background-size 属性,因为您将background-image 属性设置为a:before 元素并且背景图像的大小为256x256。但是你已经将a:before元素的widthheight定义为50px,所以背景图片的大小也应该是50px

    只需使用:

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

    看看下面的sn-p:

    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>

    希望这会有所帮助!

    【讨论】:

    • 谢谢,它只适用于background-size。但是我仍然有一个问题,为什么即使background-size 丢失,该图像的代码仍然有效。
    • @ll55 这是我的荣幸!但我还是不明白,当background-size 丢失时,什么代码在工作,也许我没有得到你的问题。
    • https://i.stack.imgur.com/zOjXI.png 中的代码即使缺少background-size 也可以在悬停图像时显示图像。
    • @ll55 因为你已经给你的:before 元素提供了width: 200pxheight: 200px,并且背景图像的实际宽度和高度在200px 左右,所以它在那里可见。但在当前场景中,您为:before 元素分配了50px 的宽度和高度,但实际图像大小为256 x 256。所以它不可见,因为它只有50 x 50 来显示图像大小。在我的回答中,我将背景图像的大小调整为:before 元素宽度和高度,即50 x 50。希望对您有所帮助!
    猜你喜欢
    • 2013-06-06
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 2017-11-23
    • 1970-01-01
    • 2015-06-08
    • 1970-01-01
    • 2020-07-22
    相关资源
    最近更新 更多