在 CSS 属性选择器中“ i”是什么意思?

我在 Google Chrome 用户代理样式表中找到了以下 CSS 选择器:

[type="checkbox" i]

i是什么意思?

5922 次浏览

正如注释中提到的,它用于不区分大小写的属性匹配

Presently it is available in Chrome 49+, Firefox 47+, Safari 9+, and Opera 37+*. Prior to this it was only available in the Chrome user-agent styles starting around Chrome 39, but could be enabled for web content by setting the experimental features flag.

* Opera 的早期版本可能也支持它。

工作示例/浏览器测试:

[data-test] {
width: 100px;
height: 100px;
margin: 4px;
}


[data-test="A"] {
background: red;
}


[data-test="a" i] {
background: green;
}
Green if supported, red if not:


<div data-test="A"></div>

The above square will be green if the browser supports this feature, red if it does not.

这是 选择器4中引入的属性选择器不区分大小写的标志。显然,他们早在2014年8月就在 Chrome 中偷偷安装了这个功能。

简而言之: 这个标志告诉浏览器匹配 type属性的各个值——不敏感。HTML 中属性值的默认选择器匹配行为是 区分大小写,这通常是不受欢迎的,因为许多属性被定义为不区分大小写的值,并且您希望确保您的选择器选择所有正确的元素,而不管大小写如何。type就是这种属性的一个例子,因为 它是枚举属性枚举属性被认为具有不区分大小写的值

以下是相关的承诺:

  • 179370 ー实施
  • 179401 — changes to UA stylesheets as shown in the screenshot in the question

请注意,它目前隐藏在“ Enable trying Web Platform Features”标志中,您可以访问 chrome://Flag/# able-economic-Web-Platform-Features。这也许可以解释为什么这个特性在很大程度上被忽视了ーー隐藏在这个标志背后的特性只能在内部使用,而不能在面向公众的代码(如作者样式表)中使用,除非它被启用,因为它们是实验性的,因此还没有准备好投入生产使用。

这里有一个你可以使用的测试用例ーー比较标志启用和禁用时的结果:

span[data-foo="bar"] {
color: red;
}


span[data-foo="bar" i] {
color: green;
}
<span data-foo="bar">If all of this text is green,</span>
<span data-foo="Bar">your browser supports case-insensitive attribute selectors.</span>

请注意,我使用了一个自定义数据属性而不是 type,以表明它可以与几乎任何属性一起使用。

I am not aware of any other implementations as of this writing, but hopefully other browsers will catch up soon. This is a relatively simple but extremely useful addition to the standard and I look forward to being able to use it in future.