Styling links based on their destination
Suppose you have lots of links on a page. You want to highlight the ones which point to example.com
- is that possible in CSS without using JavaScript?
Yes!
This scrap of code will turn all those links red:
CSS
a[href^="https://example.com"] {
color: red;
}
Now, there are a few gotchas with this code.
- It matches the string exactly. So
https://example.com
will not matchhttps://www.example.com
- The match will occur at the start of the string.
To match more lazily, you can use a substring match:
CSS
a[href*="example.com"] {
color: red;
}
That will match www.example.com
as well - but it will also match https://wikipedia.org/wiki/example.com
Is this useful?
I use it to ensure all the links which point to the Internet Archive are properly labelled:
CSS
a[href^="https://web.archive.org"]::after {
content: " (archived)";
vertical-align: super;
font-size: .9em;
}
For example, this link points to the earliest version of my website.
You could also use it to indicate when a link takes you to a specific filetype (note, this may need to be case insensitive:
CSS
/* URl ends with .pdf or .PDF */
a[href$=".pdf" i]::after {
content: " (PDF)";
vertical-align: super;
font-size: .9em;
}
It is also possible to add something to show people are leaving this site:
CSS
a[href]:not([href^="https://shkspr.mobi" i]) {
content: "↗️";
}
@Edent, I remember from Wikipedia (I ran my website with wiki at some point) that this was how they differentiates internal and external links.
Oh that's very nifty. Didn't know you could do that.
@Edent Might be an interesting read for you: https://gwern.net/design-graveyard#link-icon-css-regexps
Design Graveyard
@Edent
I think styling links based on their destination is seldom useful and have some accessibility challenges.
The external link example is missing `::after` but it would add the name of the Unicode character, "Northeast arrow with variation selector 16," to those links, pretty annoying for a screen reader user.
All major browsers now support alternative text in `content` but that's new so a fallback is called for.
https://caniuse.com/mdn-css_properties_content_alt_text
I do something similar on my website to denote links that open in a new tab (which I use to denote "external" links). I use an SVG icon, though this is less accessible than some of the other comments I'm seeing here.
@Edent I use this for transparency with Amazon affiliate links, and for a subtle differentiation of brittle external links (`a { border-bottom: 1px #369 dotted; } and stable internal links (`a[href^="/"] { border-bottom: 1px #369 solid; }`).
I did that years ago for links to PDFs on the RCP London website of the day, because I wanted it to happen automatically via CSS rather than be something I had to manually sort out. I never thought about using it to style web archive (etc) links though. That’s a very neat idea.
More comments on Mastodon.