在下面的 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;
}
当我这样做时,悬停时没有任何反应。怎么解决?
最佳答案
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;
}
关于html - CSS img 背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24193872/