3

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.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Manngo
  • 14,066
  • 10
  • 88
  • 110
  • possible duplicate of [Is there a CSS selector by class prefix?](http://stackoverflow.com/questions/3338680/is-there-a-css-selector-by-class-prefix) – dotnetom Aug 10 '15 at 04:24
  • @dotnetom Not quite, but nearly — @SBUJOLD’s answer does, however appear to be relevant. – Manngo Aug 10 '15 at 04:29

1 Answers1

5

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>
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Singular1ty
  • 2,577
  • 1
  • 24
  • 39
  • 1
    Thanks, that is how it appears, which I think is a weakness in the available selectors. The only problem with this solution is that this selector will also be satisfied with partial matches such as `not-fruit-donut`, but maybe that’s getting picky. – Manngo Aug 10 '15 at 05:14
  • @Manngo There's definitely some flaws in the CSS selectors. In a situation like the one you suggested with `not-fruit-donut`, you could duplicate the CSS and reverse the color: `p[class*=-fruit] { color: black; }`. It's far from elegant, but it is a practical solution to that specific problem. – Singular1ty Aug 10 '15 at 05:23
  • @Manngo: That's why someone else recommended my answer to the linked question earlier on - it accounts for most, if not all, possible scenarios, including the one you mention, without requiring an overriding rule. – BoltClock Aug 12 '15 at 05:00