CSS Attribute selectors允许基于属性值选择元素.不幸的是,我几年来没有使用它们(主要是因为它们不被所有现代浏览器支持).不过,我清楚地记得,通过使用类似于以下内容的代码,我能够使用它们来附加图标的所有外部链接:
- a[href=http] {
- background: url(external-uri);
- padding-left: 12px;
- }
以上代码不起作用我的问题是:它是如何工作的?如何选择所有< a> href属性以“http”开头的标签?官方的CSS规范(以上链接)甚至没有提到这是可能的.但我记得这样做.
(注意:明显的解决方案是使用类属性进行区分,我想避免这一点,因为我对HTML代码的构建方式影响不大,所有我可以编辑的是CSS代码.)
至于CSS 2.1,见
http://www.w3.org/TR/CSS21/selector.html#attribute-selectors
执行摘要:
- Attribute selectors may match in four ways:
- [att]
- Match when the element sets the "att" attribute,whatever the value of the attribute.
- [att=val]
- Match when the element's "att" attribute value is exactly "val".
- [att~=val]
- Match when the element's "att" attribute value is a space-separated list of
- "words",one of which is exactly "val". If this selector is used,the words in the
- value must not contain spaces (since they are separated by spaces).
- [att|=val]
- Match when the element's "att" attribute value is a hyphen-separated list of
- "words",beginning with "val". The match always starts at the beginning of the
- attribute value. This is primarily intended to allow language subcode matches
- (e.g.,the "lang" attribute in HTML) as described in RFC 3066 ([RFC3066]).
CSS3 also defines a list of selectors,但the compatibility varies hugely.
还有a nifty test suite显示哪些选择器在您的浏览器中工作.
至于你的例子,
- a[href^=http]
- {
- background: url(external-uri);
- padding-left: 12px;
- }
应该做的伎俩不幸的是,它不被IE支持.