【问题标题】:CSS attribute selector does not work a hrefCSS 属性选择器不起作用 a href
【发布时间】:2012-02-09 15:11:30
【问题描述】:

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

为什么背景不是红色的?

【问题讨论】:

  • +1 因为我不知道 a[attribute='AttributeName']
  • @SpaceBeers,那是element[attribute_name="attribute_value"]

标签: html css css-selectors


【解决方案1】:

在您的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/

【讨论】:

  • 属性值匹配字符串的结尾。听起来像奖金!
  • 这个答案对选择器的解释比 w3schools 更好。
【解决方案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>

如果您想确保您的规则也适用于这些情况,您可以使用匹配.pdf 属性中的任何位置

a[href*='.pdf']

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

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

【讨论】:

    猜你喜欢
    • 2017-05-21
    • 2019-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-11
    • 2015-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多