CSS

属性选择器 | 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>

结果

规范

SpecificationStatusComment
Selectors Level 4The definition of 'attribute selectors' in that specification.Working DraftAdds 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.RecommendationInitial definition

浏览器兼容性

FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support(Yes)(Yes)1.0 (1.7 or earlier)793
Case-insensitive modifier49.0No support47.0 (47.0)??9

FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support?(Yes)(Yes)1.0 (1)???(Yes)
Case-insensitive modifier?49.0No support47.0 (47.0)??949.0