完全搞懂CSS伪类选择器:is、not

本文介绍一下Css伪类:is和:not,并解释一下is、not、matches、any以前的关系css

: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.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,目前全部主流浏览器都支持,能够放心使用
复制代码

: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 github.com/w3c/csswg-d…

好了,如今知道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组合是大势所趋

相关文章
相关标签/搜索