如果已经使用了contains选择器,为什么要使用starts-with选择器 [英] If already using the contains selector, why use the starts-with selector

查看:132
本文介绍了如果已经使用了contains选择器,为什么要使用starts-with选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看其他SO问题,我了解到 * = 表示包含和 ^ = 以。。开始。我注意到一些第三方CSS代码中的 [class ^ =icon-],[class * =icon-] {/ * CSS Here * /} 这使我成为多余的;我不清楚为什么 [class * =icon-] {/ * CSS这里* /} 将不够。

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?

推荐答案

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

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 - ] 将只选择class属性的值以 code>。

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

[class * =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.


引用CodingWithSpike的注释

[class * =icon - ]也会匹配不需要的类,例如 not-icon-1 lexicon-name 这很可能是为什么包含前导空格。

[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.

本质上,选择器组用于选择所有具有至少一个以 icon - 开头的类的元素

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>

这篇关于如果已经使用了contains选择器,为什么要使用starts-with选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆