Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS regex selector match one OR another condition?

Tags:

regex

css

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'>
like image 669
Danny Avatar asked May 30 '14 20:05

Danny


People also ask

Can you use regex in CSS selector?

You can use regular expressions (regex) and cascading style sheet (CSS) selectors as operators wherever trigger filters are used. When a regular expression or CSS selector is set as the operator for a trigger, you can specify that the trigger matches the rule.

Can you combine selectors in CSS?

A CSS selector can contain more than one simple selector. Between the simple selectors, we can include a combinator. There are four different combinators in CSS: descendant selector (space)

What is attribute match in CSS?

The CSS attribute selector matches elements based on the presence or value of a given attribute.

What is regex CPP?

Regular Expression or regexes or regexp as they are commonly called are used to represent a particular pattern of string or text. Regexes are often used to denote a standard textual syntax of a string. => Visit Here To See The C++ Training Series For All.


2 Answers

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>
like image 72
Paul Roub Avatar answered Nov 11 '22 07:11

Paul Roub


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.

like image 25
James Donnelly Avatar answered Nov 11 '22 07:11

James Donnelly