2016-05-23 53 views
2

我想選擇所有<img>元素是一個<article>內,而不是內部否定一個<figure>CSS:使用上*所有元素

在這些2: How to create a css rule for all elements except one class?

https://www.w3.org/TR/css3-selectors/#negation

所有<img>是包裹在<a><p>。看起來可以用否定來完成。我的規則現在看起來像這樣:

article *:not(figure) img { border: 2px solid red; } 

任何提示技巧,爲什麼這不工作?

+1

您可以發佈重現問題所需的HTML嗎? – Pugazh

+4

爲什麼不只是爲'article img'和'figure img'指定不同的規則? https://jsfiddle.net/ds33989g/ – alex

+0

@alex想過這個,寧願稍微聰明的方式 – Vaino

回答

3

它的工作,但你告訴瀏覽器img元素必須包裝在東西。因此img直接位於article標記內的標記將不起作用,但嵌套的內容例如在div遺囑:

article *:not(figure) img { 
 
    border: 2px solid red; 
 
}
<article> 
 
    <img src="//placehold.it/50"> 
 
    <figure class="x"> 
 
    <img src="//placehold.it/50"> 
 
    </figure> 
 
    <div> 
 
    <img src="//placehold.it/50"> 
 
    </div> 
 
</article>

什麼你可能需要:

article *:not(figure) img, 
 
article > img{ 
 
    border: 2px solid red; 
 
}
<article> 
 
    <img src="//placehold.it/50"> 
 
    <figure class="x"> 
 
    <img src="//placehold.it/50"> 
 
    </figure> 
 
    <div> 
 
    <img src="//placehold.it/50"> 
 
    </div> 
 
</article>

請不要考慮的評論意見,看看你情況不允許不使用t的替代解決方案他通用*:not選擇器。例如。這可能是簡單了很多:

article img { 
 
    border: 2px solid red; 
 
} 
 

 
article figure img { 
 
    border: none; 
 
}
<article> 
 
    <img src="//placehold.it/50"> 
 
    <figure class="x"> 
 
    <img src="//placehold.it/50"> 
 
    </figure> 
 
    <div> 
 
    <img src="//placehold.it/50"> 
 
    </div> 
 
</article>

但不管是對你有用取決於整個背景。

+0

通用選擇器非常快速 - 這是一個有保證的匹配,並且無論如何可能在瀏覽器中被忽略。它是:not()這是「慢」,因爲它是瀏覽器的一個額外的指令,而且它只是「慢」,因爲它不像標記名,ID和類那樣針對關鍵路徑進行了優化。在這裏使用級聯簡直是一件容易的事 - 你並不需要爲此提出一個理由。 – BoltClock

+0

@BoltClock感謝您的反饋。這很直觀,我會接受你的話。無論如何,我不假設對選擇器的相對性能有太多瞭解。我稍微重寫了我的答案,削弱/刪除了關於選擇器速度的說法。據我所知,即使沒有perf的細節,該帖子應該能夠幫助OP。 – Jeroen