Svg filter color css

Change SVG Color with Help from CSS Filter

We no longer need to bother designers when the SVG’s color is slightly off: just filter it.

A hand holding a tinted lens that changes the color of the sea beyond from blue to purple

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.

Читайте также:  If returns error python

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.

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 , 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 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.

The quote complete with SVG quotation marks colored using CSS filter

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, a popular, open source, static site generator written in Go. Although it’s written in Go, it relies on templates 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.

 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, 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 : 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 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.

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, 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

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.

NOTR: 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.

 .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?

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 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.

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

Источник

SVG-фильтры

  • Common Words
  • HTML Tree
  • URL-encoder для SVG
  • css.yoksel.ru
  • @yoksel
  • codepen.io/yoksel

Статьи

Немного истории

Internet Explorer

  • Появились в 1997 в IE 4.0
  • Максимальная поддержка в IE 5.5
  • Выпилены в 2012 в IE 10.0

SVG-фильтры

CSS-фильтры

Общие принципы работы

CSS

CSS

CSS

SVG

SVG

SVG

SVG

SVG

Что умеют

Добавление картинки или цвета

Заливка цветом: feFlood Добавление картинки: feImage Повторение: feTile Облака: feTurbulence Облака: feTurbulence Облака: feTurbulence Облака: feTurbulence

Размытие и искажение

Размытие: feGaussianBlur Размытие: feGaussianBlur Сужение: feMorphology erode Расширение: feMorphology dilate Смещение: feOffset Волны и искажения: feDisplacementMap Тень: feDropShadow

Управление цветом

Режимы наложения: feBlend multiply Режимы наложения: feBlend screen Управление цветом: feColorMatrix hueRotate Управление цветом: feColorMatrix matrix Управление цветом: feColorMatrix luminanceToAlpha Управление каналами: feComponentTransfer Резкость: feConvolveMatrix

Источник

How to change color of SVG (Various ways using CSS)

In one of the previous articles, I have mentioned Best 5+ Free HTML Rich Text Editor to use but now in this article, I have provided few possible ways to change the color of SVG images using CSS or Javascript.

If you are using SVG image icons or SVG image logo and want to change the color of the image, then you can have an issue while changing its color, because if you will use CSS property like background-color or color for SVG files it will not work, so I have provided solutions to resolve this issue.

Change SVG color using CSS

Every SVG has XML file like structure so, it could be as below

So, if you want to change SVG color, then you can directly target » path » element or » polygon » element of SVG structure and use CSS property » fill «

So, you can have CSS has below

Here is the complete Fiddle sample

But the above solution will only work when you have SVG with path information.

You can also open SVG in any Text Editor and then get to it’s XML as shown above and then in tag use property «fill» to add change color, as shown below

Another way (Using SVG as background image)

You can also use SVG as a background image for an icon and then use CSS ‘mask’ property to fill it as Background.

Once you have set it as the background image, you can simply use ‘background-color’ CSS property to change image’s color

.icon < width: 48px; height: 48px; display: inline-block; -webkit-mask: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/18515/heart.svg) no-repeat 50% 50%; mask: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/18515/heart.svg) no-repeat 50% 50%; -webkit-mask-size: cover; mask-size: cover; >.icon-red < background-color: red; >.icon-orange < background-color: orange; >.icon-yellow

Using Filter and SVG inside IMG tag

If you are using SVG with IMG tag, you can use CSS property ‘filter’ with saturation, which will change the color of the SVG image

Using CSS Mask

We can also use CSS mask property to change SVG color

body < overflow:hidden; >.icon < --size: 70px; display: inline-block; width: var(--size); height: var(--size); transition: .12s; -webkit-mask-size: cover; mask-size: cover; >.icon-heart < background: black; animation: 4s frames infinite linear; -webkit-mask-image: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/18515/heart.svg); mask-image: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/18515/heart.svg); >@keyframes frames < 0% < transform:translatex(100vw) >25% < background: red; >75% < background: lime; >100% < transform:translatex(-100%) >>

This approach can be useful if SVG is external, and included via URL.

That’s it, these are some 4 useful ways to change color of SVG using CSS.

Источник

Оцените статью