【问题标题】:css img background colorcss img 背景颜色
【发布时间】:2014-08-03 08:05:55
【问题描述】:

在下面的 HTML 中,我有一个透明的图像

<img src="transparent.png" class="transparent" />

在样式表中,我用它来改变悬停时的背景颜色

.transparent{
    background-color: red;
}

.transparent:hover{
    background-color: blue;
}

这很好,但是,我需要将某些情况下的红色更改为绿色,所以我使用 php 来制作这样的 HTML

<img src="transparent.png" class="transparent" style="background-color: red;" />

<img src="transparent.png" class="transparent" style="background-color: green;" />

在样式表中,我省略了第一部分并留下了悬停

.transparent:hover{
    background-color: blue;
}

当我这样做时,在悬停时,什么也没有发生。怎么解决?

【问题讨论】:

  • 如果内联样式具有相同的特性,则它们会覆盖样式表。尝试将“重要”添加到样式表的 .transparent:hover
  • 不要用 PHP 改变样式,而是改变类。
  • MathiasaurusRex - S. Ahn 特别是@showdev 谢谢大家

标签: html css


【解决方案1】:

Inline styles have a higher specificity 比 CSS 文件中定义的属性。

你可以组合多个类名来实现你想要的。

.transparent {
    background-color: red;
}
.transparent:hover {
    background-color: blue;
}
.transparent.green:hover {
    background-color: green;
}

.

<img src="transparent.png" class="transparent" />       <!-- blue on hover -->
<img src="transparent.png" class="transparent green" /> <!-- green on hover -->

您应该避免使用!important 规则,因为它使以后更难覆盖这些属性。例如,在具有单独样式覆盖的页面上。 (例如不同的内容类型/页面)

具体示例

选择器也可以按如下方式编写和排序以实现该效果:

/* same specificity (one class name per selector), order counts */
.transparent:hover {
    background-color: blue;
}
.green:hover {
    background-color: green;
}

/* reversed order, but higher specificity due to two class names */
.transparent.green:hover {
    background-color: green;
}
.transparent:hover {
    background-color: blue;
}

/* The base color is always overwritten, even below here, since the
 * additional pseudo-class `:hover` again accounts for a higher
 * specificity of the above selectors. */
.transparent {
    background-color: red;
}

【讨论】:

  • 为什么.transparent.green:hover 的优先级高于.transparent:hover
  • @Youssef 因为更高的特异性。按照我的答案中的链接了解该 CSS 行为的介绍。
【解决方案2】:

您的内联样式比样式表中的规则具有更高的优先级。 要更改此设置,您可以使用 !important 关键字

.transparent:hover{
    background-color: blue !important;
}

但是使用内联样式不是最好的解决方案,使用 !important 被认为是一种不好的做法。 最好为此使用 css 类。所以你的 php 代码会添加特殊的 css 类,而不是内联样式。

【讨论】:

    【解决方案3】:

    应该可以的:

    .transparent:hover{
    background-color: blue !imporant;
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-01
      • 2016-11-26
      • 2012-06-26
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多