CSS 新选择器 :is() :where()

157 阅读2分钟

:where()  CSS 伪类函数接受选择器列表作为它的参数,将会选择所有能被该选择器列表中任何一条规则选中的元素

/* 
选择鼠标悬停时 header, main, footer元素中的任何元素
*/
:where(header, main, footer) p:hover {
  color: red;
  cursor: pointer;
}

/*
上面就相当于下面的简写
*/
header p:hover,
main p:hover,
footer p:hover {
  color: red;
  cursor: pointer;
}

:is() 用法与 :where() 相同, 不同之处在于,:where() 的优先级总是为 0,但是 :is() 的优先级是由它的选择器列表中优先级最高的选择器决定的。

可容错选择器解析

在 CSS 中使用选择器列表时,如果任何选择器无效,则整个列表被视为无效。当使用 :is() 或 :where() 而不是整个选择器列表时,如果某个选择器无法解析,则被视为无效,不正确或不受支持的选择器将被忽略,其他选择器将被使用。

即使在不支持 :unsupported 的浏览器中,仍将正确解析 :valid

:is(:valid, :unsupported) {
  /* … */
}

在不支持 :unsupported 浏览器中即使它们支持 :valid,仍将忽略。

:valid,
:unsupported {
  /* … */
}

该示例展示了 :where() 是如何起作用的,并且也阐述了 :where() 和 :is() 的区别。

跟随以下 HTML:

<article>
  <h2>:is()-styled links</h2>
  <section class="is-styling">
    <p>
      Here is my main content. This
      <a href="https://mozilla.org">contains a link</a>.
    </p>
  </section>

  <aside class="is-styling">
    <p>
      Here is my aside content. This
      <a href="https://developer.mozilla.org">also contains a link</a>.
    </p>
  </aside>

  <footer class="is-styling">
    <p>
      This is my footer, also containing
      <a href="https://github.com/mdn">a link</a>.
    </p>
  </footer>
</article>

<article>
  <h2>:where()-styled links</h2>
  <section class="where-styling">
    <p>
      Here is my main content. This
      <a href="https://mozilla.org">contains a link</a>.
    </p>
  </section>

  <aside class="where-styling">
    <p>
      Here is my aside content. This
      <a href="https://developer.mozilla.org">also contains a link</a>.
    </p>
  </aside>

  <footer class="where-styling">
    <p>
      This is my footer, also containing
      <a href="https://github.com/mdn">a link</a>.
    </p>
  </footer>
</article>

上述有例子中, 我们有两篇文章,每篇文章包含一个段落、一个侧边栏和一个页脚。它们由于使用标记子元素的不同而不同。

:is(section.is-styling, aside.is-styling, footer.is-styling) a {
  color: red;
}

:where(section.where-styling, aside.where-styling, footer.where-styling) a {
  color: orange;
}

使用一个简单选择器覆盖页脚的链接

footer a {
  color: blue;
}

这个红色的链接不起作用,因为 :is() 中的选择器会计入整体选择器的优先级,并且类选择器的优先级高于元素选择器。

然而,:where() 中的选择器的优先级是 0,所以橘色的页脚链接将被我们的简单选择器覆盖。

总结: :is() 与 :where() 的区别

  1. 优先级不同
  • :is() 优先级取决于它的选择器列表中优先级最高的选择器
  • :where() 优先级总是为 0
  1. 可容错选择器解析
  • :is() 与 :where() 都可以忽略不不正确或不受支持的选择器, 从而不影响其他样式的效果