Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS attribute selector does not work a href

I need to use attribute selector in css to change link on different color and image, but it does not work.

I have this html:

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

And this css:

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

Why isn't the background red?

like image 661
Igor Kraskynlykov Avatar asked Jan 13 '12 11:01

Igor Kraskynlykov


People also ask

Can I use HREF in CSS?

You cannot simply add a link using CSS. CSS is used for styling. You can style your using CSS.

What does CSS selector a href $= org select?

It matches links with href attributes whose values start with the given string.


2 Answers

Use the $ after your href. This will make the attribute value to match the end of the string.

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) 

source: http://www.w3.org/TR/selectors/

like image 147
Book Of Zeus Avatar answered Oct 01 '22 06:10

Book Of Zeus


The accepted answer (using a[href$='.pdf']) assumes that that a link to a pdf will always end with .pdf. That is not necessarily the case, as the link could have a query string or a hash fragment, for example with a UTM tracking code or a page number, in which case those links would not be matched. In fact depending on your application this could be the case for most links.

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

If you want to ensure your rule is also applied in those cases you could match .pdf anywhere in the attribute using

a[href*='.pdf'] 

However this will then match some unlikely but unintended things, such as a subdomain our.pdf.domain.com/a-page. But we can narrow it down further, as we know we would only use it match pdfs that have a query string or hash fragment. If we combine the 3 cases we should match all pdf links.

a[href$='.pdf'], a[href*='.pdf?'], a[href*='.pdf#'] {     background: red; } 
like image 26
inwerpsel Avatar answered Oct 01 '22 07:10

inwerpsel