CSS属性选择器允许基于属性值选择元素.不幸的是,我多年没有使用它们(主要是因为它们不受所有现代浏览器的支持).但是,我清楚地记得,通过使用类似于以下的代码,我能够使用它们来装饰带有图标的所有外部链接:
a[href=http] { background: url(external-uri); padding-left: 12px; }
上面的代码不起作用.我的问题是:它是如何工作的?如何选择属性以?开头的所有标签?官方CSS规范(上面链接)甚至没有提到这是可能的.但我确实记得这样做.
href
"http"
(注意:显而易见的解决方案是使用class
属性进行区分.我想避免这种情况,因为我对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还定义了一个选择器列表,但兼容性差异很大.
还有一个漂亮的测试套件,可以显示哪些选择器在您的浏览器中工作.
至于你的例子,
a[href^=http] { background: url(external-uri); padding-left: 12px; }
应该做的伎俩.不幸的是,IE不支持它.
安蒂的回答是足够的选择锚的,其HREF的开头HTTP,并给出可用的CSS2完美破败正则式的属性选择,就像这样:
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选择所有传出链接的适当的UPDATED方法:非伪类选择器以及新的*= substring语法,以确保它忽略可能仍以http开头的任何内部链接:
a[href^=http]:not([href*="yourdomain.com"]) { background: url(external-uri); padding-left: 12px; }
*请注意,这不受IE支持,至少IE8.谢谢,IE,你是最好的:P