CSS正则表达式选择器匹配一个或另一个条件?

时间:2014-05-30 20:39:19

标签: css regex

我想在满足/(\sclassName|^className)/时匹配,但在选择css时。假设我会使用:

[class(^|\s)='className'] {
  font-size: 5000px;
}

我找到了这个非常好的资源:The Skinny on CSS Attribute Selectors,但它没有提到这个用例。

我只想在以下两个示例中匹配“icon-”,而不是第三个。

在此,可以使用[class^='icon-]

来实现
<div class='icon-something another-class'>

在这里,这可以通过[class~='icon-']实现,但是当'icon-'位于类字符串的最开头时,这不匹配:

<div class='another-class icon-something'>

我不想在字符串中间与-icon匹配。我相信*=将匹配此|=

<div class='another-icon-class another-class'>

2 个答案:

答案 0 :(得分:19)

您需要使用具有相同规则的两个单独的选择器。 CSS选择器并不真正支持交替。

[class^='icon-'], [class*=' icon-'] {
  /* ... */
}

div {
  color: red;
}

[class^='icon-'], [class*=' icon-'] {
  color: green;
}
<div class='icon-something another-class'>should match</div>
<div class='another-class icon-something'>should match</div>
<div class='another-icon-class another-class'>should not match</div>

答案 1 :(得分:2)

您可以使用以下选择器选择其类以"icon-"开头或包含" icon-"的任何元素(请注意开头的空格):

[class^="icon-"], [class*=" icon-"] { ... }

JSFiddle demo