Styling External Links
Author: Jake Bauer | Published: 2023-03-02
Long time no see! While I have a few other, longer blog posts still cooking, I figured I’d post about a cool bit of CSS I came across on eli_oat’s site which adds a marker to every link on a site that points to an external domain.
This means that links which point to pages on the same site (or within the same domain, if configured like that) look like this: paritybit.ca, whereas links which point to any external domain look like this: example.com.
I find this super useful on sites like Wikipedia so that you know when clicking a link will take you off the site or if it will just take you to another Wikipedia article. I find it equally useful for sites that are also personal wikis or which frequently reference a mixture of original and external content. If that sounds like your site, I encourage you to add this bit of CSS too!
The original CSS as pilfered is:
a[href^="http"]:where(:not([href*="domain.tld/"]))::after {
content: "⬈"
}
Which selects all <a>
tags with attribute href
beginning with "http"
, but
not those which contain domain.tld/
, and adds an arrow symbol after the text
inside of those tags.
For my site, I’ve changed the arrow symbol to be skinnier (U+FE0E U+2197
) and
made sure this only applies inside of <article>
tags so that my <nav>
and
<footer>
are not affected. I’ve also written another small bit of CSS to make
sure that clickable images that lead to an external domain don’t have an arrow
next to them (because that looks a bit awkward). The CSS on my site is:
article a[href^="http"]:where(:not([href*="paritybit.ca/"]))::after{
content: "︎↗"
}
figure a::after{
content: "" !important
}
Images on my site are always within figure tags, and tend to be structured like:
<figure>
<a href="example.com">
<img src="example.com/img.png">
</a>
<figcaption>An image</figcaption>
</figure>
which is why this works for me, though this could also be done by adding
something like class="img"
to the <a>
tags and using that to select them instead.
If you’re using a customizable static site generator and want to make this work without CSS, or in browsers which don’t support all these CSS features (such as NetSurf or fairly old versions of Safari), you could add something similar to your website build pipeline that appends the symbol to every external link.
Another way this can be accomplished is by using the rel
attribute in the
anchor tag as detailed in this post by Martin
Christiansen
.