CSS attribute selector does not work a href

前端 未结 2 739
失恋的感觉
失恋的感觉 2020-11-30 16:58

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:



        
2条回答
  •  难免孤独
    2020-11-30 17:23

    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 PDF File
    A PDF File
    

    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;
    }
    

提交回复
热议问题