【问题标题】:background color change on hover with background-size悬停时背景颜色变化与背景大小
【发布时间】:2016-10-25 19:40:34
【问题描述】:

我有以下代码:

CSS:

<style>
    div.testy {
        border:1px solid black;
    }

    div.testy:hover {
        background-color:red;
    }
</style>

HTML:

<div class="testy" style="height:100px; 
background: url('down.png') no-repeat; background-size:contain;">
    aa
</div>

'down.png' 是具有透明背景的图像。我想做的是改变背景的颜色,同时仍然保持图像在颜色前面。

前面的代码几乎一切正常,除了当我将鼠标悬停在div 上时,什么都没有发生。

问题:为什么悬停和背景颜色更改不起作用?

这是一个出现问题的 jsfiddle 链接: https://jsfiddle.net/sdsze2fv/

【问题讨论】:

标签: html css hover background-color


【解决方案1】:

问题是您将background: 用于"background image"。分别使用background-colorbackground-image 区分background imagebackground color

div.testy {
        border:1px solid black;
    }

    div.testy:hover {
        background-color:red;

    }
<div class="testy" style="height:100px; 
background-image: url('http://www.w3schools.com/html/html5.gif'); 
background-size:contain;">
    aa
</div>

【讨论】:

  • 现在可以使用了,谢谢。有趣的是,重复也必须去掉才能工作。
【解决方案2】:

这是因为您已经在 html 中定义了 background 内联。 除非您将 !important 添加到样式中,否则内联样式始终会覆盖在 css 文件中设置的样式。

我建议您只在您的内联样式中设置background-image,然后在 CSS 文件的规则中设置background-color

div.testy {
  border:1px solid black;
}

div.testy:hover {
  background-color:red;
}
<div class="testy" style="height:100px; 
background-image: url('down.png'); background-repeat: no-repeat; background-size:contain;">
    aa
</div>

【讨论】:

    【解决方案3】:

    您设置的内联背景覆盖了 css 规则中的背景。内联样式总是覆盖任何东西(除了带有 !important 的东西)。如果您删除内联并将其放入规则中,它将起作用。或者这个里面包含了别的方法

    JSFIDDLE

    在此我们说'嘿,我希望 bkgrnd 图像是这样的'...不是背景...因为背景包括图像、颜色、重复等所有内容。它是简写。所以你在技术上也在那里设置 bkgrnd 颜色......这就是为什么它超过你的悬停。

    这是另一个选项...从内联中删除并将其放入规则中...按原样....然后它也可以工作

    JSFIDDLE2

    div.testy {
       border:1px solid black;
       height: 100px;
       font-size: 25px;
       color: orange;
       background:  url('https://upload.wikimedia.org/wikipedia/commons/3/3a/Gluecksklee_(transparent_background)2.png') no-repeat;
       background-size: contain;
    }
    
    div.testy:hover {
       background-color:red;
    }
    

    【讨论】:

      猜你喜欢
      • 2013-10-23
      • 2018-08-28
      • 2012-03-05
      • 1970-01-01
      • 2010-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-24
      相关资源
      最近更新 更多