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

时间:2015-06-30 13:56:45

标签: css css3 css-selectors

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?

1 个答案:

答案 0 :(得分:4)

它不是冗余选择器。它可能用于选择icon-类的元素,即使它是类列表中的第二个元素,如下面的代码片段所示。

[class^="icon-"]只会选择其属性值以icon-开头的元素。

[class*=" icon-"]将在其类列表中选择包含icon-类的所有元素。请注意他们之前是如何专门使用空格的。

  

引用CodingWithSpike的评论

     没有空格的

[class*="icon-"]也会匹配不需要的类,例如not-icon-1lexicon-name,这可能是为什么包含领先空间的原因。

本质上,选择器组用于选择至少一个以icon- 开头的类作为其班级列表一部分的所有元素。



[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>
&#13;
&#13;
&#13;