徹底搞懂CSS偽類選擇器:is、not


本文介紹一下Css偽類:is和:not,並解釋一下is、not、matches、any之前的關系

:not

The :not() CSS pseudo-class represents elements that do not match a list of selectors. Since it prevents specific items from being selected, it is known as the negation pseudo-class.

以上是MDN對not的解釋

單從名字上我們應該能對它有大概的認知,非選擇,排除括號內的其它元素

最簡單的例子,用CSS將div內,在不改變html的前提下,除了P標簽,其它的字體顏色變成藍色,

<div>
    <span>我是藍色</span>
    <p>我是黑色</p>
    <h1>我是藍色</h2>
    <h2>我是藍色</h2>
    <h3>我是藍色</h3>
    <h4>我是藍色</h4>
    <h5>我是藍色</h5>
</div>

之前的做法

div span,div h2,div h3, div h4,{
  color: blue;
}

not寫法

div:not(p){
  color: blue;
}

從上面的例子可以明顯體會到not偽類選擇器的作用

下面升級一下,問:將div內除了span和p,其它字體顏色變藍色

div:not(p):not(span){
  color: blue;
}

還有更為簡潔的方法,如下,但是目前兼容不太好,不建議使用

div:not(p,span){
  color: blue;
}

兼容

除IE8,目前所有主流瀏覽器都支持,可以放心使用

:is

The :is() CSS pseudo-class function takes a selector list as its argument, and selects any element that can be selected by one of the selectors in that list. This is useful for writing large selectors in a more compact form.

以上是MDN的解釋

在說is前,需要先了解一下matches

matches跟is是什么關系?

matches是is的前世,但是本質上確實一個東西,用法完全一樣

matches這個單詞意思跟它的作用非常匹配,但是它跟not作用恰好相反,作為not的對立面,matches這個次看起來確實格格不入,而且單詞不夠簡潔,所以它被改名了,這里還有一個issue https://github.com/w3c/csswg-drafts/issues/3258,也就是它改名的源頭

好了,現在知道matches和is其實是一個東西,那么is的用法是怎樣的呢?

舉例:將header和main下的p標簽,在鼠標hover時文字變藍色

<header>
  <ul>
    <li><p>鼠標放上去變藍色</p></li>
    <li><p>鼠標放上去變藍色</p></li>
  </ul>
  <p>正常字體</p>
</header>

<main>
  <ul>
    <li><p>鼠標放上去變藍色</p></li>
    <li><p>鼠標放上去變藍色</p></li>
    <p>正常字體</p>
  </ul>
</main>

<footer>
  <ul>
    <li><p>正常字體</p></li>
    <li><p>正常字體</p></li>
  </ul>
</footer>

之前的做法

header ul p:hover,main ul p:hover{
  color: blue;
}

is寫法

:is(header, main) ul p:hover{
  color: blue;
}

從上面的例子大概能看出is的左右,但是並沒有完全體現出is的強大之處,但是當選擇的內容變多之后,特別是那種層級較多的,會發現is的寫法有多簡潔,拿MDN的一個例子看下

之前的寫法

/* Level 0 */
h1 {
  font-size: 30px;
}
/* Level 1 */
section h1, article h1, aside h1, nav h1 {
  font-size: 25px;
}
/* Level 2 */
section section h1, section article h1, section aside h1, section nav h1,
article section h1, article article h1, article aside h1, article nav h1,
aside section h1, aside article h1, aside aside h1, aside nav h1,
nav section h1, nav article h1, nav aside h1, nav nav h1 {
  font-size: 20px;
}

is寫法

/* Level 0 */
h1 {
  font-size: 30px;
}
/* Level 1 */
:is(section, article, aside, nav) h1 {
  font-size: 25px;
}
/* Level 2 */
:is(section, article, aside, nav)
:is(section, article, aside, nav) h1 {
  font-size: 20px;
}

可以看出,隨着嵌套層級的增加,is的優勢越來越明顯


說完了is,那就必須認識一下any,前面說到is是matches的替代者,

any跟is又是什么關系呢?

是的,is也是any的替代品,它解決了any的一些弊端,比如瀏覽器前綴、選擇性能等

any作用跟is完全一樣,唯一不同的是它需要加瀏覽器前綴,用法如下

:-moz-any(.b, .c) {

}
:-webkit-any(.b, .c) {
    
}

結論

通過上面的介紹大概講述了css偽類is,not,matches,any它們三者的關系

is+not組合是大勢所趨

最后附上我的個人網站 https://www.mofazhuan.com/ ,轉載請著名出處


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM