Skip to main content

Targeting and styling external links using CSS

21 Jul 2020 · Last updated: 12 Sep 2024 ·
Posted in weblog#tech
Tags: css, scss

Here is the CSS snippet I use to target and show specific icons for various external links on this site. To use it, first save the external link and other brand icon SVGs in the assets directory and then set the --color-icon CSS variable somewhere.

/* Ignore URLs on this domain, internal links, anchors, and links with no-icon class */
a:not([href^='https://rsapkf.org']):not([href^='/']):not([href^='#']):not(
    .no-icon
  )::after {
  background-color: var(--color-icon);
  content: '';
  display: inline-flex;
  width: 10px;
  height: 10px;
  margin-left: 3px;
  margin-right: 1px;
  -webkit-mask-image: url(/assets/external-links/external-link.svg);
  mask-image: url(/assets/external-links/external-link.svg);
  -webkit-mask-size: cover;
  mask-size: cover;
}
a::after {
  font-size: 8px;
  padding: 0 2.25px;
  position: relative;
  bottom: 1.5px;
}
a[href*='wikipedia.org']::after {
  -webkit-mask-image: url(/assets/external-links/wikipedia.svg) !important;
  mask-image: url(/assets/external-links/wikipedia.svg) !important;
}
a[href*='github.com']::after {
  -webkit-mask-image: url(/assets/external-links/github.svg) !important;
  mask-image: url(/assets/external-links/github.svg) !important;
}

You'll also notice some links do a bumpy animation thing on hover. When clicked, they open in a new tab. These are links with target attribute set to _blank. Here is how to do it:

a[target^='_blank']:hover::after {
  position: relative;
  bottom: 0.3rem;
  transition: 0.2s ease-out;
}

Using Font Awesome

I used the following snippet previously when using SCSS with Font Awesome icons.

a {
  /* ... link styles */

  /* Target external links
     If you want to indicate websites with specific icons, make sure you add them here
     If using Font Awesome icons, font-family and font-weight need to be set based on
     whether you are using Brand or Regular icons
     https://fontawesome.com/v5.0.13/how-to-use/on-the-web/advanced/css-pseudo-elements

     Ignore internal links and specified domains (we'll style these later using brand icons) */

  &:not([href^='/']):not([href^='#']):not([href*='wikipedia.org']):not([href*='github.com'])::after {
    font-family: 'Font Awesome 5 Free';
    font-weight: 900;
    content: '\f35d'; /* external link icon unicode */
  }

  &::after {
    font-family: 'Font Awesome 5 Brands';
    font-weight: 400;
    color: rgb(85, 78, 78);
    font-size: 0.7rem;
    padding: 0.15rem;
    position: relative;
    bottom: 0.2rem;
  }

  /* Now, add individual icons from Font Awesome
     https://fontawesome.com/cheatsheet */
  &[href*='wikipedia.org']::after {
    content: '\f266';
  }

  &[href*='github.com']::after {
    content: '\f09b';
  }
}

Further reading