CSS属性选择器不能用于href

时间:2012-01-13 11:54:25

标签: html css css3 css-selectors

我需要在css中使用属性选择器来更改不同颜色和图像的链接,但它不起作用。

我有这个HTML:

<a href="/manual.pdf">A PDF File</a>

这个css:

a {
     display: block;
     height: 25px;
     padding-left: 25px;
     color:#333;
     font: bold 15px Tahoma;
     text-decoration: none;
 }
 a[href='.pdf'] { background: red; }

为什么背景不是红色?

2 个答案:

答案 0 :(得分:173)

在href之后使用$。这将使属性值与字符串的结尾匹配。

a[href$='.pdf'] { /*css*/ }

JSFiddle:http://jsfiddle.net/UG9ud/

E[foo]        an E element with a "foo" attribute (CSS 2)
E[foo="bar"]  an E element whose "foo" attribute value is exactly equal to "bar" (CSS 2)
E[foo~="bar"] an E element whose "foo" attribute value is a list of whitespace-separated values, one of which is exactly equal to "bar" (CSS 2)
E[foo^="bar"] an E element whose "foo" attribute value begins exactly with the string "bar" (CSS 3)
E[foo$="bar"] an E element whose "foo" attribute value ends exactly with the string "bar" (CSS 3)
E[foo*="bar"] an E element whose "foo" attribute value contains the substring "bar" (CSS 3)
E[foo|="en"]  an E element whose "foo" attribute has a hyphen-separated list of values beginning (from the left) with "en" (CSS 2)

来源:http://www.w3.org/TR/selectors/

答案 1 :(得分:2)

接受的答案(使用a[href$='.pdf'])假定pdf链接将始终以.pdf结尾。情况并非一定如此,因为链接可能具有查询字符串或哈希片段,例如带有UTM跟踪代码或页码,在这种情况下,这些链接将不匹配。实际上,对于大多数链接,情况可能取决于您的应用程序。

<a href="/manual.pdf?utm_source=homepage">A PDF File</a>
<a href="/manual.pdf#page=42">A PDF File</a>

如果您想确保在这种情况下也应用规则,则可以使用{p> 1来匹配属性中任何地方的.pdf

a[href*='.pdf']

但是,这将匹配一些不太可能但意外的内容,例如子域our.pdf.domain.com/a-page。但是我们可以进一步缩小范围,因为我们知道我们只会将其与具有查询字符串或哈希片段的pdf匹配使用。如果将这三种情况结合起来,我们应该匹配所有pdf链接。

a[href$='.pdf'], a[href*='.pdf?'], a[href*='.pdf#'] {
    background: red;
}
相关问题