CSS 选择器“(A 或 B)和 C”?
这应该很简单,但我找不到它的搜索词。
假设我有这个:
<div class="a c">Foo</div>
<div class="b c">Bar</div>
在 CSS 中,如何创建一个与“(.a 或 .b) 和 .c”相匹配的选择器?
我知道我可以这样做:
.a.c,.b.c {
/* CSS stuff */
}
但是,假设我必须经常使用各种逻辑组合来执行这种逻辑,是否有更好的语法?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不可以。CSS 的
or
运算符 (,
) 不允许分组。它本质上是选择器中优先级最低的逻辑运算符,因此您必须使用.ac,.bc
。No. CSS'
or
operator (,
) does not permit groupings. It's essentially the lowest-precedence logical operator in selectors, so you must use.a.c,.b.c
.对于那些阅读本文 >= 2021 的人:
我使用
:is()
选择器取得了成功:For those reading this >= 2021:
I found success using the
:is()
selector:还没有,但是有一个实验性的
:is()
(以前的:matches()
)伪类选择器可以做到这一点:您可以找到更多关于它的信息 < a href="http://css-tricks.com/almanac/selectors/m/matches/" rel="noreferrer">此处 和 这里。目前,大多数浏览器都支持其初始版本
:any()
,其工作方式相同,但将被:is()
取代。我们只需要再等一会儿,然后再到处使用它(我肯定会的)。Not yet, but there is the experimental
:is()
(formerly:matches()
) pseudo-class selector that does just that:You can find more info on it here and here. Currently, most browsers support its initial version
:any()
, which works the same way, but will be replaced by:is()
. We just have to wait a little more before using this everywhere (I surely will).如果你有这样的:
并且你只想选择具有
.x
和(.a
或.b
)的元素,你可以写:但只有当您有三个“子类”并且您想选择其中两个时,这才方便。
仅选择一个子类(例如
.a
):.ax
选择两个子类(例如
.a
和.b
):.x:not(.c)
选择所有三个子类:
.x
If you have this:
And you only want to select the elements which have
.x
and (.a
or.b
), you could write:but that's convenient only when you have three "sub-classes" and you want to select two of them.
Selecting only one sub-class (for instance
.a
):.a.x
Selecting two sub-classes (for instance
.a
and.b
):.x:not(.c)
Selecting all three sub-classes:
.x
不。标准 CSS 不提供您正在寻找的那种东西。
但是,您可能需要查看 LESS 和 SASS。
这两个项目旨在通过引入附加功能(包括变量、嵌套规则和其他增强功能)来扩展默认 CSS 语法。
它们允许您编写更加结构化的 CSS 代码,并且它们中的任何一个几乎肯定会解决您的特定用例。
当然,没有一个浏览器支持它们的扩展语法(特别是因为这两个项目都有不同的语法和功能),但它们所做的是提供一个“编译器”,将您的 LESS 或 SASS 代码转换为标准 CSS,然后您可以部署在您的网站上。
No. Standard CSS does not provide the kind of thing you're looking for.
However, you might want to look into LESS and SASS.
These are two projects which aim to extend default CSS syntax by introducing additional features, including variables, nested rules, and other enhancements.
They allow you to write much more structured CSS code, and either of them will almost certainly solve your particular use case.
Of course, none of the browsers support their extended syntax (especially since the two projects each have different syntax and features), but what they do is provide a "compiler" which converts your LESS or SASS code into standard CSS, which you can then deploy on your site.