发布于 2026-01-06 1 阅读
0

使用 :is 伪类缩短您的 CSS 选择器 DEV 的全球展示挑战赛,由 Mux 呈现:展示您的项目!

使用 :is 伪类缩短您的 CSS 选择器

由 Mux 赞助的 DEV 全球展示挑战赛:展示你的项目!

我希望在发现:is 伪类之前很久就知道 CSS 的一个特性。

你可以用它来缩短一些较长的选择器。

例如,考虑以下声明块:

h1 a, h2 a, h3 a, h4 a, h5 a, h6 a {
    /* some styles would go here */
}
Enter fullscreen mode Exit fullscreen mode

感觉有点重复,对吧?

现在,如果我们想给每个标签添加一个类,我们的代码将这样扩展<a>

h1 a.class, h2 a.class, h3 a.class, h4 a.class, h5 a.class, h5 a.class {
    /* some styles would go here */
}
Enter fullscreen mode Exit fullscreen mode

我们需要重新输入“ .class六次

这只是:is选择器如何帮你节省击键次数的一个小例子:

:is(h1, h2, h3, h4, h5, h6) a {
    /* some styles would go here */
}
Enter fullscreen mode Exit fullscreen mode

在这种情况下,如果我们想添加之前提到的那个类,只需要输入一次,而不是六次:

:is(h1, h2, h3, h4, h5, h6) a.class {
    /* some styles would go here */
}
Enter fullscreen mode Exit fullscreen mode

所以基本上,它所做的就是遍历每个以逗号分隔的内部选择器,并将其应用于同级或子选择器。

绩效影响

关于 CSS,需要记住的重要一点是,选择器语法上的细微差别会对性能产生指数级的影响。

例如,`" div > p"` 的性能远不如 `" div p"`,因为浏览器是从右到左解析选择器。虽然这方面我以后可能会写更多,但这超出了本文的讨论范围。

所以就:is选择器而言,我只想指出伪类(包括:is)是不高效的选择器类型

此外,浏览器兼容性还有待提高。我强烈建议考虑使用一些具有相同功能的向后兼容的伪类,例如“ :matches()”。

结论

希望您喜欢这篇文章,也希望它能为您节省未来的时间!

此外,谁愿意每次有细微变化就坐下来重写每个选择器六遍呢?

文章来源:https://dev.to/natclark/shorten-your-css-selectors-with-the-is-pseudo-class-ig4