CSS 属性选择器不工作 href

我需要在 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; }

为什么背景不是红色的?

72156 次浏览

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

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

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/

接受的答案(使用 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>

如果您想确保您的规则也适用于这些情况,您可以使用

a[href*='.pdf']

然而,这将匹配一些不太可能但意想不到的东西,如子域 our.pdf.domain.com/a-page。但是我们可以进一步缩小范围,因为我们知道我们只使用它来匹配具有查询字符串或散列片段的 pdf。如果我们结合3种情况,我们应该匹配所有的 pdf 链接。

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