2017-03-08 16 views
6

例如以風格標準輸入我寫的東西,如:如何覆蓋具有許多否定(:不)的選擇器?

input:not([type="checkbox"]):not([type="radio"]) { 
    background-color: blue; 
} 

不過,所以如果我想用一個類我必須這樣做來覆蓋它增加特異性很多:

.red.red.red { 
    background-color: red; 
} 

有沒有辦法在不改變功能的情況下降低原始輸入選擇器的特異性?

+0

您可以隨時使用'important'覆蓋專一! –

+0

https://specificity.keegan.st/使用此找到正確的選擇器 – DaniP

+3

@MichaelCoker是的,但是破壞了特異性。我儘量保持特異性儘可能低,對我而言,使用'.red.red.red'是比'!important'更好的解決方案。 – joshhunt

回答

3

不幸的是,在選擇器3,這是因爲:not()你能做的最好的只接受一個簡單的選擇。話雖如此,重寫規則中的選擇器可以替換爲input.red.red - 除了該規則必須在樣式表中早些出現之外,您不需要比屬性選擇器更多的類選擇器。

這是選擇器4通過其增強:not()解決的另一個問題:特異性。在選擇器4中,您將能夠用一個:not()僞代替所有這些否定,從而將原始選擇器內的特異性有效地降至僅一個屬性選擇器。 From section 16

a:not()僞類的特異性被其選擇器列表參數中最具體的複雜選擇器的特異性替換。

由於任何屬性選擇器與類選擇器同樣具體,因此列表中任意數量的單獨屬性選擇器的特性永遠不會超過其中的一個。這使您可以避免僅使用一個類選擇器進行覆蓋,而無需重複執行。

以下works in Safari作爲證明的概念:

/* 1 type, 2 attributes -> specificity = (0, 2, 1) 
 
input:not([type="checkbox"]):not([type="radio"]), 
 
    1 type, 1 attribute -> specificity = (0, 1, 1) */ 
 
input:not([type="checkbox"], [type="radio"]) { 
 
    background-color: blue; 
 
} 
 

 
/* 1 type, 1 class  -> specificity = (0, 1, 1) */ 
 
input.red { 
 
    background-color: red; 
 
}
<input type="checkbox"> 
 
<input type="radio"> 
 
<input type="text"> 
 
<input class="red" type="text">

1

這可能讓你周圍的特殊性問題:

input:not([type="checkbox"]):not([type="radio"]):not(.red)) { 
 
    background-color: blue; 
 
} 
 

 
.red { 
 
    background-color: red; 
 
}
<input type="checkbox"><br> 
 
<input type="radio"><br> 
 
<input class="red">

+1

這很有創意我會給你:D。不幸的是,它不是很實用,因爲你希望'.red'繼承原始樣式,但能夠覆蓋原始樣式。我的例子沒有顯示這個,對不起。 – joshhunt

+1

是的,我不知道所有的細節,所以我拋出了一個概念。我知道這是一個遠射。 –

+0

謝謝,我很欣賞這種努力! – joshhunt