本文介紹一下Css僞類:is和:not,並解釋一下is、not、matches、any以前的關係css
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.html
以上是MDN對not的解釋git
單從名字上咱們應該能對它有大概的認知,非選擇,排除括號內的其它元素github
最簡單的例子,用CSS將div內,在不改變html的前提下,除了P標籤,其它的字體顏色變成藍色,web
<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寫法bash
div:not(p){
color: blue;
}
複製代碼
從上面的例子能夠明顯體會到not僞類選擇器的做用ide
下面升級一下,問:將div內除了span和p,其它字體顏色變藍色性能
div:not(p):not(span){
color: blue;
}
複製代碼
還有更爲簡潔的方法,以下,可是目前兼容不太好,不建議使用字體
div:not(p,span){
color: blue;
}
複製代碼
除IE8,目前全部主流瀏覽器都支持,能夠放心使用
複製代碼
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這個單詞意思跟它的做用很是匹配,可是它跟not做用剛好相反,做爲not的對立面,matches這個次看起來確實格格不入,並且單詞不夠簡潔,因此它被更名了,這裏還有一個issue github.com/w3c/csswg-d…
舉例:將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的替代者,
是的,is也是any的替代品,它解決了any的一些弊端,好比瀏覽器前綴、選擇性能等
any做用跟is徹底同樣,惟一不一樣的是它須要加瀏覽器前綴,用法以下
:-moz-any(.b, .c) {
}
:-webkit-any(.b, .c) {
}
複製代碼
經過上面的介紹大概講述了css僞類is,not,matches,any它們三者的關係
is+not組合是大勢所趨