属性选择器 | Attribute selectors
属性选择器
CSS属性选择器
根据给定属性是否存在或属性的值匹配元素。
/* <a> elements with a title attribute */
a[title] {
color: purple;
}
/* <a> elements with an href matching "https://example.org" */
a[href="https://example.org"] {
color: green;
}
/* <a> elements with an href containing "example" */
a[href*="example"] {
font-size: 2em;
}
/* <a> elements with an href ending ".org" */
a[href$=".org"] {
font-style: italic;
}
[attr]
表示具有属性名attr
的元素。
实例
链接
CSS
a {
color: blue;
}
/* Internal links, beginning with "#" */
a[href^="#"] {
background-color: gold;
}
/* Links with "example" anywhere in the URL */
a[href*="example"] {
background-color: silver;
}
/* Links with "insensitive" anywhere in the URL,
regardless of capitalization */
a[href*="insensitive" i] {
color: cyan;
}
/* Links that end in ".org" */
a[href$=".org"] {
color: red;
}
HTML
<ul>
<li><a href="#internal">Internal link</a></li>
<li><a href="http://example.com">Example link</a></li>
<li><a href="#InSensitive">Insensitive internal link</a></li>
<li><a href="http://example.org">Example org link</a></li>
</ul>
结果
语言
CSS
/* All divs with a `lang` attribute are bold. */
div[lang] {
font-weight: bold;
}
/* All divs in US English are blue. */
div[lang~="en-us"] {
color: blue;
}
/* All divs in Portuguese are green. */
div[lang="pt"] {
color: green;
}
/* All divs in Chinese are red, whether
simplified (zh-CN) or traditional (zh-TW). */
div[lang|="zh"] {
color: red;
}
/* All divs with a Traditional Chinese
`data-lang` are purple. */
/* Note: You could also use hyphenated attributes
without double quotes */
div[data-lang="zh-TW"] {
color: purple;
}
HTML
<div lang="en-us en-gb en-au en-nz">Hello World!</div>
<div lang="pt">Olá Mundo!</div>
<div lang="zh-CN">世界您好!</div>
<div lang="zh-TW">世界您好!</div>
<div data-lang="zh-TW">世界您好!</div>
结果
规范
Specification | Status | Comment |
---|---|---|
Selectors Level 4The definition of 'attribute selectors' in that specification. | Working Draft | Adds modifier for ASCII case-insensitive attribute value selection |
Selectors Level 3The definition of 'attribute selectors' in that specification. | Recommendation | |
CSS Level 2 (Revision 1)The definition of 'attribute selectors' in that specification. | Recommendation | Initial definition |
浏览器兼容性
Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | 1.0 (1.7 or earlier) | 7 | 9 | 3 |
Case-insensitive modifier | 49.0 | No support | 47.0 (47.0) | ? | ? | 9 |
Feature | Android | Chrome for Android | Edge | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile | Chrome for Android |
---|---|---|---|---|---|---|---|---|
Basic support | ? | (Yes) | (Yes) | 1.0 (1) | ? | ? | ? | (Yes) |
Case-insensitive modifier | ? | 49.0 | No support | 47.0 (47.0) | ? | ? | 9 | 49.0 |