Manngo
Manngo

Reputation: 16281

CSS pipe selector with multiple classes

Suppose I have two elements with multiple classes:

<p class="fruit-apple something">First</p>
<p class="whatever fruit-banana">Second</p>

How can I use the “pipe” selector (|=) to select the fruit- classes?

I have tried something like the following but this seems not to work.

p[class|=fruit] {
    color: red;
}
<p class="fruit-apple something">First</p>
<p class="whatever fruit-banana">Second</p>

This is clearly because in the second case, the class string does not begin with fruit-, and the selector is matching naively.

Upvotes: 3

Views: 904

Answers (1)

Singular1ty
Singular1ty

Reputation: 2615

The |= selector only selects the starting portion of the specified attribute.

You'll want the *= operator instead.

p[class*=fruit-]

It will search for classes that contain the phrase fruit-x where x is anything you want.

p[class*=fruit-] {
    color: red;
}
<p class="fruit-apple something">First</p>
<p class="whatever fruit-banana">Second</p>
<p class="whatever fruit">Third (No selection)</p>
<p class="fruit noselect">Fourth (No selection)</p>

Upvotes: 5

Related Questions