Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple matching substring selectors

I'm trying to create a rule to match all classes beginning with icon- which also have the btn class. [class^="icon-"] { matches the first condition, but how do I add "that also have the .btn class?

like image 219
Echilon Avatar asked May 18 '12 15:05

Echilon


People also ask

Can I use multiple 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)

How do you group multiple selectors?

To group selectors, separate each selector with a comma.

What are multiple selectors in CSS?

When you group CSS selectors, you apply the same styles to several different elements without repeating the styles in your stylesheet. Instead of having two, three, or more CSS rules that do the same thing (set the color of something to red, for example), you use a single CSS rule that accomplishes the same thing.


2 Answers

This works:

.btn[class*="icon-"]

So will,

[class*="icon-"][class~="btn"]

Check out my fiddle: http://jsfiddle.net/VaACP/1/

like image 75
Rob Lowe Avatar answered Nov 11 '22 02:11

Rob Lowe


Finding icon- at the Start

You could try the following - the icon class would need to be first in the attribute:

[class^='icon-'].btn

To this HTML

<div class="icon-1 btn">Foo</div>  <!-- Matched -->
<div class="icon-2 btn">Bar</div>  <!-- Matched -->
<div class="btn icon-3">Fizz</div> <!-- Not Matched -->
<div class="icon btn">Buzz</div>   <!-- Not Matched -->

Finding icon- Within (Caution!)

You could modify the query to base the class search on a substring:

[class*='icon-'].btn

But note that this will turn up positive with classes that resemble icon-, like myicon-1 or noicon-2.

Finding icon- Anywhere Within

If you're unsure of where the icon- class will show up in the attribute, you could look for both examples:

[class^='icon-'].btn, [class*=' icon-'].btn

This will find icon- classes at the beginning, or anywhere within (preceded by a space).

<div class="icon-1 btn">Foo</div>  <!-- Matched -->
<div class="icon-2 btn">Bar</div>  <!-- Matched -->
<div class="btn icon-3">Fizz</div> <!-- Matched -->
<div class="icon btn">Buzz</div>   <!-- Not Matched -->
like image 41
Sampson Avatar answered Nov 11 '22 03:11

Sampson