A CSS Selector for External Links

Have you ever wanted to quickly select all of the external links on your site, so that you could put a little icon showing that they would take the user away from your domain, or even open in a new tab? Here's a quick little recipe for it using the power :not() CSS pseudo-class and a list of attribute selectors on the href property:

)::after {
  content: "↗";
  margin-inline-start: 1ch;

How pretty is that!

We've selected all the a (or anchor) tags that don't have an href property that either:

  • starts with "#": this is for in-page anchor tags
  • starts with "/": this is for relative links
  • contains your site's origin: you'll have to hard-code this or make it a CSS variable
  • contains "localhost": this covers you while your developing the site

I learned very recently that you could use special syntax with attribute selectors that allow you to check for more if the attribute simply equals some value, but rather if it contains (*=) or starts with (^=) some value, and even more.

Furthermore, I just learned that you can place a comma-separated list into the :not() pseudo-class, and the selection will be excluded if any of the items match.

What I've shown here simply puts an arrow character after the link, but you could use background-image to get a proper SVG icon placed after each link fairly easily.

Happy coding! ✨🚫🤙🏻