Change SVG Color with Help from CSS Filter
Tags: css
Published: 2022-09-08 13:43:26

---
title: Change SVG Color with Help from CSS Filter
published: true
date: 2022-09-05 00:00:00 UTC
tags: css
canonical_url: https://www.paigeniedringhaus.com/blog/change-svg-color-with-help-from-css-filter
---

[![A hand holding a tinted lens that changes the color of the sea beyond from blue to purple](https://www.paigeniedringhaus.com/static/459f029bc6f08e419153e98400650cc5/15ec7/filter.jpg "A hand holding a tinted lens that changes the color of the sea beyond from blue to purple")](/static/459f029bc6f08e419153e98400650cc5/0f98f/filter.jpg)

## Introduction

Working with talented designers is such a pleasure as a web developer. Not only do they come up with beautiful layouts for pages and simplify complex concepts into easy to understand visuals, but oftentimes they provide me the opportunity to learn a new web development technique to bring their visions to life.

I recently had such an opportunity while building a new About Us page for my company's marketing site. In the mockup, the page had a large quote by our founder, and the quotation marks around the text were stylized SVG images. When the designer gave me the SVGs, however, they came in a standard black color which didn't match the blue color in the design.

Before I asked my designer to recreate new SVGs to match the color in the design (or attempt to alter the SVG's color myself), I did a little digging online and found a useful CSS technique: `filter`. With `filter`, I was able to change the SVG's color myself - and change it to any hue I desired - no bothering my designer required.

**In this post, we'll explore CSS `filter` and see how it can be used to alter SVG image colors to match colors in mockups.**

I'll even share a handy website that will generate `filter` combinations to exactly replicate CSS hex colors.

Below is a video showing how the CSS filter affects the color of quotation mark SVGs - note how they change from black to light blue.

 
{% youtube yvoxS52JyoM %} 

---
 
## CSS Filter

Before I share the solution, let's take a closer look at CSS `filter` - it wasn't a technique that I was familiar with prior to this.

According to the MDN documents about **[CSS `filter`](https://developer.mozilla.org/en-US/docs/Web/CSS/filter)**, it's used to apply graphical effects like blur or color shift to an element. Some standard CSS functions include:

- `blur` - make the image fuzzier or sharper.
- `contrast` - adjust the contrast of an image's colors.
- `grayscale` - convert an image to grayscale.
- `drop-shadow` - apply a blurred, offset version of the image, drawn in a specific color and composited below the image.

In addition to these standard functions, an SVG can also be referenced with a URL to an SVG filter element - essentially, a custom filter.

> This article doesn't go into great detail about how the filter functions work because they're quite complex. If you want a full rundown of what they are and how they work, I recommend checking out the [Mozilla documentation](https://developer.mozilla.org/en-US/docs/Web/CSS/filter#functions) for more info.

Now what the documents fail to highlight is that multiple of these functions can be combined _together_ in a single function to great effect - like, say, changing an SVG's color, which is what we're going to cover next.

## Filters in action

[![The quote complete with SVG quotation marks colored using CSS filter](https://www.paigeniedringhaus.com/static/2b1ff9d4a9b63b3a28cba059b06a8399/1e043/svg-color-hero.png "The quote complete with SVG quotation marks colored using CSS filter")](/static/2b1ff9d4a9b63b3a28cba059b06a8399/7960f/svg-color-hero.png)

_The final quote with its light blue SVG quotation marks._

Ok, let me show you how we can use these filter functions in your own code. The first thing you'll need is some HTML elements to apply this CSS to.

### Set up the HTML, SVGs, and the img-quote class

The site I was working on happens to be made with [Hugo](https://gohugo.io/), a popular open source static site generator written in Go. Although it's written in Go, it relies on [templates](https://gohugo.io/templates/introduction/) to render the majority of the site's HTML, so the example code below should look relatively familiar to you if you know HTML.

> **A note on templates:**
> 
> If you've ever used React's JSX components, Node.js with Pug or Handlebars, or Jekyll - Hugo's templates are similar: HTML elements with Go variables and functions sprinkled in with `{{ }}` to render the correct information wherever the template's injected.

Here's the code below for the quote section. For the purposes and clarity of this post, I've replaced the Go variables injected into the template with the generated HTML.

`quote-template.html`

```html
    <section class="quote-section">
      <div class="container">
        <div class="row">
          <div class="col-12">
            <h2 class="text-center quote-text">
              <img
                class="quote-img"
                src="/images/about/quote-left-solid.svg"
                alt="decorative left quotation mark"
              />
              Complexity kills. It sucks the life out of developers.
              <div />
              It makes products difficult to plan, build, test, deliver, and support.
              <img
                class="quote-img"
                src="/images/about/quote-right-solid.svg"
                alt="decorative right quotation mark"
              />
            </h2>
            <div class="text-center">
              <h4 class="text-center quote-source">
                Ray Ozzie
                <span class="quote-source-role">
                  Founder & CEO, Blues Wireless
                </span>
              </h4>
            </div>
          </div>
        </div>
      </div>
    </section>
```

While this section of code is relatively small, it still deserves discussion. In addition to the HTML elements, there's quite a few CSS classes present, many of which are courtesy of **[Bootstrap](https://getbootstrap.com/)**, one of the original open source CSS frameworks for responsive web development.

Among the custom classes like `quote-section` and `quote-img`, which I used for custom styling, there are ones like `container`, `row`, `col-12`, and `text-center`. All of the latter examples are Bootstrap classes and serve to do things like have the quote text take up the entire width of the page: `col-12`, or center the text inside the `<div>`: `text-center`.

These classes are beside the point though, the one you want to focus on for this post is the **`quote-img`** class attached to the two `<img>` elements: these are the two quotation mark SVGs bookending the quote.

This `quote-img` class is how we're going to attach the CSS `filter` functions to both quotation mark SVGs and make sure they're both the correct color to match the design.

### Add the CSS filter to quote-img

As I mentioned above, the SVGs my designer gave me were standard black, but in the design mockup, the quotes were a lighter shade of blue: hex color `#94BBD0`.

When I started looking for a solution to change the color of these SVGs, I came across [this answer on StackOverflow](https://stackoverflow.com/questions/22252472/how-to-change-the-color-of-an-svg-element/53336754#53336754).

While there were suggestions in the answer thread that amounted to modifying the SVG's source code directly (not something I was keen to do), but luckily I didn't have to.

The solution I landed on not only illustrated how CSS `filter` could be used to modify the SVG's color, it also linked to a **[helpful CodePen](https://codepen.io/sosuke/pen/Pjoqqp)**, which allowed me to input the hex color I wanted (`#94BBD0`), and it spit out the exact CSS filter combination to create it (plus an accuracy reading of just how close to perfect the CSS filter code was to matching the original hex color). And all I had to do was copy the code produced to use in my own CSS file. What an amazing timesaver!

[![CodePen to translate any SVG to a particular hex color](https://www.paigeniedringhaus.com/static/bdf451f230f33fbbc20a3d0867ec2fef/1e043/css-svg-to-hex-converter.png "CodePen to translate any SVG to a particular hex color")](/static/bdf451f230f33fbbc20a3d0867ec2fef/ec2ae/css-svg-to-hex-converter.png)

_CodePen to translate any SVG to a particular hex color: https://codepen.io/sosuke/pen/Pjoqqp. Bless the developer who went to the trouble of making this!_

So in my own SCSS file that was added to help style the About Us page's HTML, add the following class and the code copied from the CSS filter code generator.

> **Note:** Even though this file shown in the example code is SCSS instead of pure CSS, for this post it shouldn't make a difference. It should be a direct 1:1 comparison.

`about.scss`

```scss
  .quote-img {
    height: 26px;
    filter: invert(84%) sepia(9%) saturate(1100%) hue-rotate(165deg)
      brightness(88%) contrast(83%);
    margin-bottom: 16px;
  }
```

A careful combination of multiple filter functions like `invert`, `sepia` and others, and voila - the exact shade of blue to match the hex code.

To make the image quotes the proper size and placement in relation to the text, in addition to changing their color, I also needed to set the height of the SVGs to `26px` and give them a bottom margin of `16px` to push them up to look like they were surrounding the text instead of sitting centered inline with the text.

And now the SVGs are correct color to match the mockup without designer intervention required - and can easily be changed in the future, if need be. How convenient is that?

---

## Conclusion

Great designs have the power to capture people's attention and help them understand the benefits of a particular product or company - and many times they help the developers bringing these designs to life learn a new thing or two along the way.

As I was building a new page for my company's website that featured a large quote from our company founder, I was faced with just such a scenario where the stylized quotation marks were given to me as black SVG images, but they were shown in the design as being blue.

Before asking my designer to take the time recreate them in the appropriate color to match the design, I did some preliminary googling and found a much more flexible, code driven solution making great use of CSS `filter`.

And not only did the answer exist, but someone had also made a [CodePen](https://codepen.io/sosuke/pen/Pjoqqp) that could match any hex color! Just what I needed, and there for anyone to benefit from. The web development community can be so awesomely generous.

Check back in a few weeks — I’ll be writing more about JavaScript, React, IoT, or something else related to web development.

If you’d like to make sure you never miss an article I write, sign up for my newsletter here: https://paigeniedringhaus.substack.com

Thanks for reading. I hope this cool trick to convert SVGs from one color to another using CSS's `filter` comes in handy for you like it did for me. It's a great feeling as a developer to have the power to make these sorts of changes through code.

## References & Further Resources

- [MDN Docs, CSS Filter](https://developer.mozilla.org/en-US/docs/Web/CSS/filter)
- [StackOverflow thread](https://stackoverflow.com/questions/22252472/how-to-change-the-color-of-an-svg-element/53336754#53336754) for CSS filter solution
- [CodePen site to match SVG to any hex color via CSS filter](https://codepen.io/sosuke/pen/Pjoqqp)