用于识别多个类的 CSS 速记

2022-01-10 00:00:00 regex css-selectors css

我阅读了关于在 CSS 选择器中使用正则表达式的本教程并试图推断:是否有 CSS 速记来执行以下操作?我想选择具有a"、b"、c"或d"附加类的foo"类的所有 div.

I read this tutorial on using regular expressions with CSS selectors and am trying to extrapolate: Is there a CSS shorthand to do the following? I want to select all div's with class of "foo" that have either an additional class of "a", "b", "c", or "d".

    .foo.a,
    .foo.b,
    .foo.c,
    .foo.d {
       /* stuff */
    }

类似:

.foo[class~='a','b','c','d'] {} ?

推荐答案

目前不可能(使用 Selectors 3 建议).CSS 没有成熟的正则表达式语法,也没有办法分解多个选择器列表的一部分.

It's not possible, currently (with the Selectors 3 recommendation). There isn't a full-fledged regex grammar for CSS, nor is there a way to crunch down parts of multiple selector lists.

Selectors 4 提出了一个新的 :matches() 基于 Mozilla 原始 :any() 实现的伪类(参见 this answer 了解一些历史):

Selectors 4 proposes a new :matches() pseudo-class based on Mozilla's original :any() implementation (see this answer for a bit of history):

.foo:matches(.a, .b, .c, .d)

当然,不要指望浏览器支持这一点.我什至可能会忘记在那个时候更新这个答案,但是......我们会看到的.

Of course, don't expect browser support for this yet. I might even forget to update this answer when that time comes but... we'll see.

相关文章