簡體   English   中英

CSS img背景顏色

[英]css img background color

在以下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;
}

當我這樣做時,懸停時沒有任何反應。 怎么解決呢?

內聯樣式比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;
}

內聯樣式的優先級高於樣式表中的規則。 要更改此設置,您可以使用!important關鍵字

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

但是,使用內聯樣式不是最佳解決方案,而使用!important被認為是不好的做法。 最好使用CSS類。 因此,您的php代碼將添加特殊的CSS類,而不是內聯樣式。

那應該工作:

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM