开发者

CSS Shorthand to identify multiple classes

开发者 https://www.devze.com 2023-03-24 09:05 出处:网络
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

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 */
    }

something like:开发者_运维技巧

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


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 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.


Maybe .foo[class~='a'][class~='b'][class~='c'][class~='d'] ?


No, your first way of writing it is the correct way. You can only search for one match at time with an attribute selector so the closest thing that's a mixture of your two methods is:

.foo[class~="a"],
.foo[class~="b"],
.foo[class~="c"],
.foo[class~="d"] {
   /* stuff */
}

Which really isn't shorthand or anything :P The best way to select by classes is just the ordinary way with a .className. Attribute selectors are only really helpful for selecting other attributes, or if you have a class that begins with a certain word and are using css3. For example you could use something like:

.foo[class^="mah-class"]{ }

Which would match mah-class-a mah-class-b mah-classAHHH... etc

0

精彩评论

暂无评论...
验证码 换一张
取 消