Explain Codes LogoExplain Codes Logo

Css attribute selector does not work a href

html
css
selectors
pdf
Nikita BarsukovbyNikita Barsukov·Aug 10, 2024
TLDR

If your a[href] CSS attribute selector is mysteriously misbehaving, ensure your selector's match is identical to your href value in your HTML link.

a[href="exact-url"] { /*Imagine your CSS is wizard's magic wand */ }

Partial matches have got you covered with more options: ^= (starts with), $= (ends with), and *= (contains):

a[href^="https://"] { /* HTTPS means it's secure, right? Right?! */ } a[href$=".pdf"] { /* Because gray is too mainstream for PDFs */ } a[href*="site.com"] { /* If only the boss knew about this */ }

Just be certain that no other stronger rule is flexing its muscles to override your CSS

If you're doing some interior design for PDF links, the $= selector looks for URLs ending in .pdf:

a[href$='.pdf'] { background-color: red; /* PDFs deserve attention, background red as Mars! */ }

Dealing with Query Strings and Anchors

Got query strings or anchors in the URL? Here are the selectors to the rescue:

/* Grabs every href with a berserk '.pdf' before '?' */ a[href*='.pdf?'] { /* styles */ } /* Captures every href with a '.pdf' before '#' */ a[href*='.pdf#'] { /* styles */ }

These can form a super team for more complete styling:

a[href$='.pdf'], a[href*='.pdf?'], a[href*='.pdf#'] { /* They worked as a team and solved the PDF links mystery */ }

Minding your syntax

Always stay hyper-alert for CSS syntax gremlins; a lone miscreant quote or bracket could spell modern catastrophe for your selector.

Validate, validate, validate. Make sure the link is an <a> tag with href attribute directing to a PDF.

Making use of other attributes

For more finesse in your design, you can double-date with href and other attributes:

/* Directs all the 'downloadable' links leading to a prom (*.pdf) */ a[href$=".pdf"][data-downloadable="yes"] { /* styles */ }

Getting the hierarchy right

Sometimes, it's not the attribute selector causing issues, but another rule flexing its specificity muscles:

#content a[href$=".pdf"] { /* This beefed-up selector is stealing your show! */ }

Playing in the JSFiddle sandbox

Try out different link scenarios in the JSFiddle playground to see how your selectors perform. Test out the PDF attribute selectors in action here: JSFiddle Example.