返回

可读性与更短选择器:CSS 2020 Level 4新伪类

前端

CSS 2020 Level 4带来了两个有趣且实用的新伪类: :is():where(),它们旨在缩短选择器的长度,同时保持或提高CSS代码的可读性。

CSS 选择器,简介:

CSS 选择器用于指定需要被格式化的元素,如<p><h1>.my-class。选择器可以很简单,如:where(p),也可以很复杂,如:

p.special-class:not(.other-class) > a:hover

上面这个选择器选择的是所有<p>元素,它们具有.special-class类,不具有.other-class类,并且包含一个:hover状态的<a>元素。

:is() 与 :where() 新伪类的用法与价值:

  1. 缩短选择器长度:

is():where() 伪类都可以用来缩短选择器长度。例如:

a[href="https://example.com"]

可以使用 :is() 伪类缩短为:

:is(a[href="https://example.com"])

或者,可以使用 :where() 伪类缩短为:

:where(a[href="https://example.com"])

缩短后的选择器不仅更简洁,而且也更具可读性。

  1. 合并多个选择器:

is():where() 伪类可以用来合并多个选择器。例如:

p.special-class, div.special-class

可以使用 :is() 伪类合并为:

:is(p.special-class, div.special-class)

或者,可以使用 :where() 伪类合并为:

:where(p.special-class, div.special-class)

合并后的选择器不仅更简洁,而且也更具可读性。

  1. 创建更复杂的选择器:

is():where() 伪类可以用来创建更复杂的选择器。例如:

p:is(.special-class):not(.other-class) > a:hover

可以使用 :is() 伪类缩短为:

:is(p.special-class):not(.other-class) > :is(a:hover)

或者,可以使用 :where() 伪类缩短为:

:where(p.special-class):not(.other-class) > :where(a:hover)

缩短后的选择器不仅更简洁,而且也更具可读性。

结论:

is():where() 伪类是CSS 2020 Level 4中引入的两个非常有用的新功能。它们可以用来缩短选择器长度,合并多个选择器,并创建更复杂的选择器。这些功能的引入使CSS代码更简洁、更具可读性,从而提高了开发者的生产力和代码维护性。