Danny
Danny

Reputation: 4124

CSS regex selector match one OR another condition?

I'd like to match when /(\sclassName|^className)/ is satisfied, but when selecting css. Hypothetically I would use like:

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

I've found this resource, which is very nice: The Skinny on CSS Attribute Selectors, but it doesn't mention this use case.

I just want to match "icon-" in the following 2 examples, but not the 3rd.

Here, this can be achieved with [class^='icon-]

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

Here, this can be achieved with [class~='icon-'], but this does not match when 'icon-' is at the very beginning of the class string:

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

I do not want to match this, with -icon in the middle of a string. I believe *= will match this one, as will |= :

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

Upvotes: 11

Views: 38726

Answers (2)

Paul Roub
Paul Roub

Reputation: 36458

You'll need to use two separate selectors with the same rule. CSS selectors don't really support alternation.

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

Upvotes: 30

James Donnelly
James Donnelly

Reputation: 128836

You can use the following selectors to select any element whose class either starts with "icon-" or contains " icon-" (note the space at the start):

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

JSFiddle demo.

Upvotes: 3

Related Questions