A CSS Selector for External Links

A quick little CSS tip for how to apply styles to all your external links.

A seedling-stage note

Last tended May 7, 2023 originally posted May 7, 2023

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:

a:not(
	[href^="#"],
	[href^="/"],
	[href*="localhost"],
	[href*="your-site-origin.com"]
)::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:

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! ✨🚫🤙🏻