Image: Hover state on :before pseudo-element.

CSS Tip: How to change the color of an SVG Graphic

During my work on a custom website today, the designer had specified a graphic before an off-site link. That’s very useful in letting users know that they will be leaving the site they’re on, and possibly opening a new browser window. The challenge for me was adding that graphic without having to create a custom template. CSS to the rescue!

Normally, I would use FontAwesome to add the icon. But this site isn’t currently using FontAwesome, and there’s no need to add the additional fonts and CSS just for one icon. Instead, I created an SVG image and placed it on the server.

Then, I used the :before pseudo-element on the link. Pseudo-elements are the method used by CSS to create elements on the webpage that aren’t actually in the HTML code. The “content” definition calls the image, just like an image HTML tag. Because the SVG is black and the designer wanted a gray icon, the opacity was set to 0.65 to slightly lighten the image.

.teaser .links a {
  display: inline-block;
  font-size: 28px;
  text-transform: uppercase;
  color: #000;
}
.teaser .a:before {
  display: inline-block;
  content: url("../img/new-tab.svg");
  width: 28px;
  position: relative;
  top: 3px;
  opacity: 0.65;
}

Next, I add a :hover state to the link to change the color to green:

.teaser .links a:hover {
  color: #00a450;
}

Now we get to the really trick part: changing the now-gray icon to a light green. After getting the HEX color code from Photoshop, I used this nifty CSS color generator tool on CodePen to get the filter values needed to change the color of the element using CSS. Here is the final CSS for the a:hover:before state:

.teaser .links a:hover:before {
  filter: invert(86%) sepia(3%) saturate(776%) hue-rotate(76deg) brightness(96%) contrast(89%);
  opacity: 1;  
}