Styling External Links Using :has and an Attribute Selector

No doubt this has been written about before, but I used this approach yesterday and it’s cool so I’m writing about it too.

Like any good website, I have a pile of links in the footer of this one. Most of the links are to internal pages. A handful of them are to external sites. It’s never bothered me before that the external links aren’t marked as such. But, in a usual fit of procrastination while writing my previous post, I decided those external links now had to be marked in some way.

Each link is an a wrapped in an li element. I’m lazy, so I decided to avoid using any image and instead use the ↗ character. I wasn’t procrastinating so hard that I wanted to create, export, and upload an image.

I didn’t want the ↗ to be in the a itself, but after it in the containing li. I could have used a class on each li to do this, but instead I used the :has selector plus a starts with (^) attribute selector to include the ↗ character in an ::after element.

.footer__links li:has([href^="https"])::after {
  content: "↗";
}

This says; “Style any li element that contains any element with an href value that starts with ‘https’.”. So <a href='/about'> doesn’t get styled, but <a href='https://example.org'> does.

An enlarged screenshot of the footer links on tylergaw.com
fig 1. The external footer links now marked as such with the ↗ character.

I haven’t had many times where I’ve reached for :has or the starts with attribute selector, but they sure are helpful. Here’s a CodePen with an isolated example of this.

This is yet another reminder that:

CSS IS GOOD
fig 2. Learn it. Know it. Live it.

If you have thoughts about this post, send me an email at me@tylergaw.com.