1

Looking at other SO questions, I've learnt that *= means "contains" and ^= means "starts with". I noticed [class^="icon-"], [class*=" icon-"] {/* CSS Here */} in some third-party CSS code. This strikes me as redundant; I am unclear why [class*=" icon-"] {/* CSS Here */} would not have been sufficient.

Does the redundant use of the ^= selector serve any purpose (e.g., readability, older browser support, etc.)?

Question reference:
What is caret symbol ^ used for in css when selecting elements?
What does an asterisk before an equal sign mean (*=) ? What about the exclamation mark?

Community
  • 1
  • 1
Brian
  • 25,523
  • 18
  • 82
  • 173
  • Where is that construct used? Looks redundand and should probably be `[class*="icon-"]` (No space, just one selector) – Amit Jun 30 '15 at 14:04
  • 2
    Harry's answer is correct. A similar explanation is also given here: http://stackoverflow.com/questions/3338680/is-there-a-css-selector-by-class-prefix/8588532#8588532 – BoltClock Jun 30 '15 at 15:21
  • 1
    @Harry: Learnt and Learned are both correct. Learned is more common in the U.S. – Brian Jun 30 '15 at 15:31
  • @Brian: Oh sorry I didn't know that. Thanks for the comment :) My main intent was to correct the typo in the title and add the tag. – Harry Jun 30 '15 at 15:33

1 Answers1

4

It is not a redundant selector. It is possibly used to select the elements with icon- class even if it is second one in the class list like in the below snippet.

[class^="icon-"] will only select the elements whose value for class attribute starts with icon-.

[class*=" icon-"] will select all elements that contain a class with icon- in its list of classes. Note how they have specifically used a space before.

Quoting CodingWithSpike's comment

[class*="icon-"] without a space would also match undesired classes like not-icon-1 or lexicon-name which is likely why the leading space is included.

In essence the selector group is used to select all elements who have at least one class which begins with icon- as part of their class list.

[class^="icon-"] {
  color: green;
}
[class*=" icon-"] {
  color: red;
}
[class^="icon-"],
[class*=" icon-"] {
  background: beige;
}

[class*="icon-"]{
  border: 1px solid brown;
}
<div class="icon-1">Only Icon class</div>
<div class="a icon-1">Some other class before</div>
<div class="a not-icon-1">Some other class before</div>
Harry
  • 87,580
  • 25
  • 202
  • 214
  • 4
    `[class*="icon-"]` without a space would also match undesired classes like `not-icon-1` or `lexicon-name` which is likely why the leading space is included. – CodingWithSpike Jun 30 '15 at 14:34
  • @CodingWithSpike: Absolutely spot on. I didn't think of that :) – Harry Jun 30 '15 at 14:36