Brian
Brian

Reputation: 25834

If already using the contains selector, why use the starts-with selector

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?

Upvotes: 1

Views: 438

Answers (1)

Harry
Harry

Reputation: 89750

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>

Upvotes: 4

Related Questions