1136

I want to use this technique and change the SVG color, but so far I haven't been able to do so. I use this in the CSS, but my image is always black, no matter what.

My code:

.change-my-color {
  fill: green;
}
<svg>
    <image class="change-my-color" xlink:href="https://svgur.com/i/AFM.svg" width="96" height="96" src="ppngfallback.png" />
</svg>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Barbara
  • 12,908
  • 6
  • 32
  • 43

43 Answers43

1439

2020 answer

CSS Filter works on all current browsers

To change any SVGs color

  1. Add the SVG image using an <img> tag.

    <img src="dotted-arrow.svg" class="filter-green"/>
    
  2. To filter to a specific color, use the following Codepen (click here to open the codepen) to convert a hexadecimal color code to a CSS filter:

    For example, output for #00EE00 is

    filter: invert(42%) sepia(93%) saturate(1352%) hue-rotate(87deg) brightness(119%) contrast(119%);
    

    Generate a filter for any color here.

  3. Add the CSS filter into this class.

    .filter-green{
        filter: invert(48%) sepia(79%) saturate(2476%) hue-rotate(86deg) brightness(118%) contrast(119%);
    }
    
Westy92
  • 19,087
  • 4
  • 72
  • 54
Manish Menaria
  • 23,899
  • 3
  • 21
  • 23
  • 10
    This comes with the usual caveat about not being supported in older browser versions: https://developer.mozilla.org/en-US/docs/Web/CSS/filter#Browser_compatibility – Kevin Wang Mar 20 '19 at 19:00
  • 148
    As noted in the CodePen, if your SVG isn't black (mine was grey), adding `brightness(0) saturate(100%)` to the beginning of the list of filters will first turn it 100% black, which enables the other filters to change it to the correct color. – jdunning Apr 11 '19 at 16:57
  • 7
    Also, lots of fascinating background on the solution in this [StackOverflow question](https://stackoverflow.com/questions/42966641/how-to-transform-black-into-any-given-color-using-only-css-filters/43960991#43960991) that informed the CodePen. – jdunning Apr 11 '19 at 17:05
  • 11
    My guy. The support seems acceptable https://caniuse.com/#feat=css-filters. – Sam Doidge Nov 07 '19 at 15:20
  • 4
    works so well, used this unaffiliated codepen to get my hex into a filter: https://codepen.io/sosuke/pen/Pjoqqp – WEBjuju Mar 12 '20 at 13:41
  • 22
    but how do you specify a particular color ? – phil123456 Oct 19 '20 at 06:37
  • This is great! I dynamically change the color of an SVG in a React app using the npm package [hex-to-css-filter](https://github.com/willmendesneto/hex-to-css-filter#usage) – virgiliogm Feb 11 '21 at 12:52
  • Pressing the button in the link provided seems to have no effect at all. – HoldOffHunger Mar 25 '21 at 16:04
  • 2
    from a black svg, you can get the "filter values" for any color with the following tool: https://codepen.io/sosuke/pen/Pjoqqp – bloub Jul 15 '21 at 07:42
  • 2
    We can just write ```...```. Worked for me perfectly. – Barefaced Bear Jul 18 '21 at 04:37
  • 3
    Should mention how to calculate this for any color: https://isotropic.co/hex-color-to-css-filter/ – Cybernetic Nov 28 '21 at 01:25
  • Any ways to apply a filter to an image used as the background of an element? – Rune FS Dec 07 '21 at 20:17
  • What makes a thousand ones think this is better than leave it as and apply CSS fill:color into it? – rlatief Feb 24 '22 at 23:31
  • I don't recommend using `filter` to invert colors in an image [because that will create a new stacking-context](https://stackoverflow.com/questions/25764404/why-does-stacking-order-change-on-webkit-filter-hover) (which messes-up `position`ed elements and z-indexing). When I need to invert colors or similar I just create a second separate image, though I appreciate this doesn't work for dynamically-generated or user-supplied images. – Dai Apr 12 '22 at 06:46
  • Duplicate of that earlier answer, should have been an edit instead: https://stackoverflow.com/a/49049008/3795597 – MayeulC Jul 21 '22 at 16:17
  • Seems to be working well with .png images as well. Sick! – Maksim Dimitrov Sep 01 '22 at 19:45
  • 2
    I wish I could just pass a CSS color name for this – ICW Nov 27 '22 at 23:11
  • This approach worked to change the entire svg to a single color. I'm curious if there's a way to apply one filter to the "fill" and another filter to the "stroke" (I think that's the svg term for the lines/outlines"? – AppDreamer Feb 23 '23 at 17:27
  • And how do I achieve a gradient instead of a single color? – trueToastedCode Apr 10 '23 at 14:53
  • 2
    Wow! Couldn't be any more cryptic than that! Whatever happend to a simple: `filter: #ff0000`? – Jeach May 13 '23 at 07:14
  • Thanks! I tried a lot of solutions but this was the only one that worked reliably (without inlining or manually editing multiple svg files). Honestly I'm very surprised that it's 2023 and something as simple as changing an svg color dynamically is so unintuitive and complicated. – SirDorius Jul 02 '23 at 13:44
  • I had some issues with the provided filter generator. This one seemed more accurate: https://angel-rs.github.io/css-color-filter-generator/ – SnazzyPencil Jul 06 '23 at 11:36
521

To change the color of any SVG, you can directly change the SVG code by opening the SVG file in any text editor. The code may look like the below code:

<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 16.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     width="500px" height="500px" viewBox="0 0 500 500" enable-background="new 0 0 500 500" xml:space="preserve">

    <g>
        <path d="M114.26,436.584L99.023,483h301.953l-15.237-46.416H114.26z M161.629,474.404h-49.592l9.594-29.225h69.223
                 C181.113,454.921,171.371,464.663,161.629,474.404z"/>

    /* Some more code goes on */
    </g>
</svg>

You can observe that there are some XML tags like path, circle, polygon, etc.. There you can add your own color with help of the style attribute. Look at the below example

<path fill="#AB7C94" d="M114.26,436.584L99.023,483h301.953l-15.237-46.416H114.26z M161.629,474.404h-49.592l9.594-29.225h69.223
                        C181.113,454.921,171.371,464.663,161.629,474.404z"/>

Add the style attribute to all the tags so that you can get your SVG of your required color.

As per Daniel's comment, we can use fill attribute directly instead of fill element inside style attribute.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sushant Pachipulusu
  • 5,499
  • 1
  • 18
  • 30
  • 141
    Why not just using attribute `fill` like this: `fill = "#AB7C94"` ? Not sure why the `style` attribute is needed – bg17aw Jan 27 '17 at 19:24
  • 7
    Hi Daniel, yeah it works. I didn't knew that fill can be used as an attribute. Sorry for not noticing your comment so long @bg17aw – Sushant Pachipulusu Apr 30 '18 at 09:08
  • 5
    This should be the best answer because it provides the same result which much less code. Less code, better code. – NDi Dec 12 '20 at 05:32
  • 1
    If you don't want to change the color of the svg programmatically, this is the best and easiest solution. Thank you! – Torben Jul 30 '21 at 13:10
  • as note, this method change the source file (base color), if you need change the color dynamically, you can use the css code like the `Manish Menaria` [answer](https://stackoverflow.com/a/53336754/8979042).. – Fauzan Edris Sep 22 '21 at 08:33
  • 1
    Problem I see is, if we need may different colors. Its will increase the size of project & slower the page loading. But SVG's are normally small in size. In my case its not a problem to add few images. But this is a good answer. Thanks! – Dinith Rukshan Kumara Sep 22 '21 at 16:44
  • Use the color attribute to change the color of an SVG element: `color="#ffffff"`, fill will just fill out the SVG with color, not change the color. – Marten Oct 01 '21 at 23:19
438

If you want to change the color dynamically:

  1. Open the SVG in a code editor

  2. Add or rewrite the attribute of fill of every path to fill="currentColor"

  3. Now, that svg will take the color of your font color, so you can do something like:

    svg {
        color : "red";
    }
    
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mártin Alcalá
  • 4,589
  • 1
  • 7
  • 13
344

You can't change the color of an image that way. If you load SVG as an image, you can't change how it is displayed using CSS or JavaScript in the browser.

If you want to change your SVG image, you have to load it using <object>, <iframe> or using <svg> inline.

If you want to use the techniques in the page, you need the Modernizr library, where you can check for SVG support and conditionally display or not a fallback image. You can then inline your SVG and apply the styles you need.

See:

#time-3-icon {
   fill: green;
}

.my-svg-alternate {
  display: none;
}
.no-svg .my-svg-alternate {
  display: block;
  width: 100px;
  height: 100px;
  background-image: url(image.png);
}
<svg width="96px" height="96px" viewBox="0 0 512 512" enable-background="new 0 0 512 512" xml:space="preserve">
<path id="time-3-icon" d="M256,50C142.229,50,50,142.229,50,256c0,113.77,92.229,206,206,206c113.77,0,206-92.23,206-206
    C462,142.229,369.77,50,256,50z M256,417c-88.977,0-161-72.008-161-161c0-88.979,72.008-161,161-161c88.977,0,161,72.007,161,161
    C417,344.977,344.992,417,256,417z M382.816,265.785c1.711,0.297,2.961,1.781,2.961,3.518v0.093c0,1.72-1.223,3.188-2.914,3.505
    c-37.093,6.938-124.97,21.35-134.613,21.35c-13.808,0-25-11.192-25-25c0-9.832,14.79-104.675,21.618-143.081
    c0.274-1.542,1.615-2.669,3.181-2.669h0.008c1.709,0,3.164,1.243,3.431,2.932l18.933,119.904L382.816,265.785z"/>
</svg>

<image class="my-svg-alternate" width="96" height="96" src="ppngfallback.png" />

You can inline your SVG. Tag your fallback image with a class name (my-svg-alternate):

<svg width="96px" height="96px" viewBox="0 0 512 512" enable-background="new 0 0 512 512" xml:space="preserve">
<path id="time-3-icon" .../>
</svg>

<image class="my-svg-alternate" width="96" height="96" src="ppngfallback.png" />

And in CSS use the no-svg class from Modernizr (CDN: http://ajax.aspnetcdn.com/ajax/modernizr/modernizr-2.7.2.js ) to check for SVG support. If there isn't any SVG support, the SVG block will be ignored and the image will be displayed, otherwise the image will be removed from the DOM tree (display: none):

.my-svg-alternate {
  display: none;
}
.no-svg .my-svg-alternate {
  display: block;
  width: 100px;
  height: 100px;
  background-image: url(image.png);
}

Then you can change the color of your inlined element:

#time-3-icon {
   fill: green;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
helderdarocha
  • 23,209
  • 4
  • 50
  • 65
  • 19
    You cannot style embedded `object` SVGs from the hosting document. – Javier Rey Nov 11 '18 at 04:27
  • 2
    @JavierRey you could inject the styling into the object tag's contents via javascript. But you're right that it does not apply if you just add it to the hosting document's stylesheet. – Robert Longson Dec 31 '18 at 11:21
  • 3
    I'm using the solution from @manish-menaria and it works perfectly. – Ryan Ellis Mar 01 '19 at 12:51
  • 3
    Accepted answer should be changed to: https://stackoverflow.com/a/53336754/467240 – mtyson Jan 12 '20 at 20:27
  • sometimes you just need to remove the def tag inside your SVG file, because if you have it, your CSS rules will not be applied: `` `` – FelipeCaparelli Jul 29 '20 at 19:41
  • 1
    this answer makes no sense, where is the svg image file name ??? , why use viewbox or enable background ? what if you want to change the color, and not the background ? – phil123456 Oct 19 '20 at 06:33
  • 5
    There is a way to do it, just give the svg fill="currentColor" property, than it will get color from CSS color assigned to it (font color). See this answer https://stackoverflow.com/a/65147574/8230784 – justdvl Apr 27 '21 at 02:15
  • We can just write ```...```. Worked for me perfectly. – Barefaced Bear Jul 18 '21 at 04:36
  • 1
    This was a great answer a few years ago but CSS Filter effects have totally changed the game. This answer isn't actually the correct one any longer. That makes me so happy as a web dev... progress! – Memetican Sep 09 '22 at 09:26
105

Only SVG with path information. You can't do that to the image... as the path you can change stroke and fill information and you are done. like Adobe Illustrator

So, via CSS you can overwrite the path fill value:

path { fill: orange; }

But if you want a more flexible way as you want to change it with a text when having some hovering effect going on, use:

path { fill: currentColor; }

body {
  background: #ddd;
  text-align: center;
  padding-top: 2em;
}

.parent {
  width: 320px;
  height: 50px;
  display: block;
  transition: all 0.3s;
  cursor: pointer;
  padding: 12px;
  box-sizing: border-box;
}

/***  desired colors for children  ***/
.parent{
  color: #000;
  background: #def;
}
.parent:hover{
  color: #fff;
  background: #85c1fc;
}

.parent span{
  font-size: 18px;
  margin-right: 8px;
  font-weight: bold;
  font-family: 'Helvetica';
  line-height: 26px;
  vertical-align: top;
}
.parent svg{
  max-height: 26px;
  width: auto;
  display: inline;
}

/****  magic trick  *****/
.parent svg path{
  fill: currentcolor;
}
<div class='parent'>
  <span>TEXT WITH SVG</span>
  <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="128" height="128" viewBox="0 0 32 32">
<path d="M30.148 5.588c-2.934-3.42-7.288-5.588-12.148-5.588-8.837 0-16 7.163-16 16s7.163 16 16 16c4.86 0 9.213-2.167 12.148-5.588l-10.148-10.412 10.148-10.412zM22 3.769c1.232 0 2.231 0.999 2.231 2.231s-0.999 2.231-2.231 2.231-2.231-0.999-2.231-2.231c0-1.232 0.999-2.231 2.231-2.231z"></path>
</svg>
</div>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Biskrem Muhammad
  • 4,074
  • 3
  • 31
  • 38
64

Solution 1 - Edit SVG to point to the currentColor

<svg>... fill: currentColor stroke: currentColor ...</svg>

Then you can control the color of the stroke and the fill from your CSS content:

svg {
  color: blue; /* Or any color of your choice. */
}

Pros and cons:

  • Simple and uses conventional supported CSS.

Suitable if:

  • You control the SVG
  • SVG can be included inline in the HTML.

Solution 2 - CSS mask property

<i class="icon"></i>
  .icon {
    -webkit-mask-size: cover;
    mask-size: cover;
    -webkit-mask-image: url(https://url.of.svg/....svg);
    mask-image: url(https://url.of.svg/....svg);
    background-color: blue; /* Or any color of your choice. */
    width: 20px;
    height: 20px;
  }

}

Pros and cons

  • Relatively easy to use
  • Browser support for the mask CSS property is partial.

Suitable if:

  • SVG is external, and included via URL
  • Meant to be used on modern known browsers.

Solution 3 - CSS Filter property - static color

If the color is known in advance, you can use https://codepen.io/sosuke/pen/Pjoqqp to find the filter needed to change your SVG to the desired color. For example, to convert the svg to #00f:

<img src="https://url.of.svg/....svg" class="icon">
.icon {
    filter: invert(8%) sepia(100%) saturate(6481%) hue-rotate(246deg) brightness(102%) contrast(143%);
}

If your original color isn't black, prefix the list of filters with brightness(0) saturate(100%) to convert it first to black.

Pros and cons:

  • There might be a small, nonsignificant difference between the result and the desired color.

Suitable if:

  • Desired color is known in advance.
  • External image
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ben Carp
  • 24,214
  • 9
  • 60
  • 72
  • On Solution 3 pros and cons; it might be worth adding that using multiple filters on complex SVG images have a huge negative impact on performance. And should be used sparingly if at all. – umbriel Apr 21 '22 at 13:46
  • The C style `/* */` [is the ***only*** valid comment character sequence in CSS](https://stackoverflow.com/questions/2479351/why-do-comments-work-in-stylesheets-but-comments-dont). Otherwise, the consequence is likely silently ignored CSS content. [A CSS validator](https://jigsaw.w3.org/css-validator/) will report an error: "`7 Parse Error // Or any color of your choice. width: 20px`" – Peter Mortensen Jan 12 '23 at 19:05
  • Thanks @PeterMortensen !! That's what happens when you edit your code on Stackoverflow instead of the code editor ... – Ben Carp Jan 14 '23 at 19:44
  • 1
    How can I like this multiple times! This was it. If the original color isn't black you really need to first convert to black by prefixing with 'brightness(0) saturate(100%)' Was really helpful – Chidiebere Ezeokwelume Aug 17 '23 at 07:23
57

I added a test page - to color SVG via Filter settings:

For example,

filter: invert(0.5) sepia(1) saturate(5) hue-rotate(175deg)

Upload & Color your SVG - Jsfiddle

I took the idea from: Swapping Fill Color on Image Tag SVGs

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Yonatan Ayalon
  • 1,959
  • 18
  • 19
  • 2
    Thanks, you just save me from myself. `.custom-disabled > svg {filter:invert(0.2) sepia(1) saturte(0) hue-rotate(0);}` did just the job I need to disabled icon. – roger Mar 18 '18 at 10:29
33

SVG mask on a box element with a background color will result:

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-bike {
  background: black;
  animation: 4s frames infinite linear;
  
  -webkit-mask-image: url(https://image.flaticon.com/icons/svg/89/89139.svg);
  mask-image: url(https://image.flaticon.com/icons/svg/89/89139.svg);
}

@keyframes frames {
  0% { transform:translatex(100vw) }
  25% { background: red; }
  75% { background: lime; }
  100% { transform:translatex(-100%) }
}
<i class="icon icon-bike" style="--size:150px"></i>

Note - SVG masks are not supported in Internet Explorer browsers

vsync
  • 118,978
  • 58
  • 307
  • 400
  • 4
    Thanks a lot, @vsync this is just the best hack around for what I need. – Vixson Jun 17 '20 at 12:45
  • This is great. However with this approach, we use the img alt field, for accessibility. Any idea on how to bring that back? Thanks! – Will59 Sep 26 '22 at 11:57
  • 1
    @Will59 - use the [ARIA rules](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/img_role): `` – vsync Sep 26 '22 at 14:03
19

The easiest way would be to create a font out of the SVG using a service like https://icomoon.io/app/#/select or such. Upload your SVG, click "generate font", include font files and CSS content into your side and just use and style it like any other text. I always use it like this because it makes styling much easier.

But as mentioned in the article commented by @CodeMouse92, icon fonts mess up screen readers (and are possibly bad for SEO). So rather stick to the SVGs.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Felix Hagspiel
  • 2,634
  • 2
  • 30
  • 43
  • 7
    It also messes up screen readers. See ["Death to Icon Fonts" by Seren Davies](https://www.youtube.com/watch?v=9xXBYcWgCHA) – CodeMouse92 Mar 31 '17 at 20:55
  • Icon fonts are not bad for SEO. Not understanding how SEO works is what is bad for SEO. Learn about Section 508, ADA, and WCAG, and then you'll understand how to use font icons even better based on do's and don'ts. The video you referenced has been viewed 8500 times with 111 likes. You take this as religion? – Pegues Aug 02 '22 at 15:35
14

You can try to color it with this css filter hack:

.colorize-pink {
  filter: brightness(0.5) sepia(1) hue-rotate(-70deg) saturate(5);
}

.colorize-navy {
  filter: brightness(0.2) sepia(1) hue-rotate(180deg) saturate(5);
}

.colorize-blue {
  filter: brightness(0.5) sepia(1) hue-rotate(140deg) saturate(6);
}
warfish
  • 613
  • 5
  • 20
14

To change the color of an SVG element, I have found out a way while inspecting the Google search box search icon below:

.search_icon {
  color: red;
  fill: currentColor;
  display: inline-block;
  width: 100px;
  height: 100px;
}
<span class="search_icon">
    <svg focusable="false" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M15.5 14h-.79l-.28-.27A6.471 6.471 0 0 0 16 9.5 6.5 6.5 0 1 0 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path></svg>
</span>

I have used a span element with "display:inline-block", height, width and setting a particular style "color: red; fill: currentColor;" to that span tag which is inherited by the child svg element.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sarang Kakkoth
  • 381
  • 3
  • 9
13

To simply change the color of the SVG file:

Go to the SVG file and under styles, mention the color in fill:

<style>.cls-1{fill: #FFFFFF;}</style>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sethu Sathyan
  • 187
  • 1
  • 4
12

Target the path within the 'svg' tag:

<svg>
   <path>....
</svg>

You can do it inline, like:

<path fill="#ccc">

Or

svg{
   path{
        fill: #ccc
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Uzair Khan
  • 2,812
  • 7
  • 30
  • 48
11

You can change SVG coloring with CSS if you use some tricks. I wrote a small script for that.

  • go through a list of elements which do have an SVG image
  • load the SVG file as XML
  • fetch only the SVG part
  • change color of path
  • replace src with the modified SVG image as an inline image
$('img.svg-changeable').each(function () {
  var $e = $(this);
  var imgURL = $e.prop('src');

  $.get(imgURL, function (data) {
    // Get the SVG tag, ignore the rest
    var $svg = $(data).find('svg');

    // Change the color
    $svg.find('path').attr('fill', '#000');

    $e.prop('src', "data:image/svg+xml;base64," + window.btoa($svg.prop('outerHTML')));
  });

});

The code above might not be working correctly. I've implemented this for elements with an SVG background image which works nearly similar to this.

But anyway, you have to modify this script to fit your case.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
cydoc
  • 199
  • 1
  • 6
  • By the way: If you are a RoR developer, you can add a new method for the sass precompiler which can do the job too. This is much better because you will have the base64 encoded, correct colored image in your compiled css file. No JS needed anymore! Maybe I could provide the code I have written, have to talk to the CTO. – cydoc Jul 17 '15 at 07:01
  • 4
    +1 for providing a solution, rather than saying it can't be done. This answer is also relevant: https://stackoverflow.com/questions/11978995/how-to-change-color-of-svg-image-using-css-jquery-svg-image-replacement – Claytronicon Nov 27 '17 at 18:59
11
  1. Method 1

    The easy and effect way:

    Open your .svg file with any text editor

    <svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg"
       xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
       viewBox="0 0 477.526 477.526" style="enable-background:new 0 0 477.526 477.526;
       fill: rgb(109, 248, 248);" xml:space="preserve">
    <svg />
    

    Give an style attribute and fill that with color.

  2. Another way

    Fill with color in your shape. Here i have rect shape fill="white".

    <svg width="800" height="600" xmlns="http://www.w3.org/2000/svg">
        <g>
            <title>background</title>
            <rect fill="#fff" id="canvas_background" height="602" width="802" y="-1"
             x="-1"/>
    
                <g display="none" overflow="visible" y="0" x="0" height="100%" width="100%"
                   id="canvasGrid">
    
                   <rect fill="url(#gridpattern)" stroke-width="0" y="0" x="0" height="100%"
                   width="100%"/>
                </g>
        </g>
    </svg>
    
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MD SHAYON
  • 7,001
  • 45
  • 38
9

2022 Web Component <load-file> answer

This (7 line) native Web Component (JSWC) loads external content, and injects it into the DOM.

It is explained and documented in my DEV blog post: <load-file> Web Component.

Full source code:

customElements.define("load-file", class extends HTMLElement {

  // declare default connectedCallback as sync so await can be used
  async connectedCallback(
      // call connectedCallback with parameter to *replace* SVG (of <load-file> persists)
      src = this.getAttribute("src"),
    // attach a shadowRoot if none exists (prevents displaying error when moving Nodes)
    // declare as parameter to save 4 Bytes: 'let '
    shadowRoot = this.shadowRoot || this.attachShadow({mode:"open"})
  ) {
      // load SVG file from src="" async, parse to text, add to shadowRoot.innerHTML
    shadowRoot.innerHTML = await (await fetch(src)).text()

    // append optional <tag [shadowRoot]> Elements from inside <load-svg> after parsed <svg>
    shadowRoot.append(...this.querySelectorAll("[shadowRoot]"))

    // if "replaceWith" attribute
    // then replace <load-svg> with loaded content <load-svg>
    // childNodes instead of children to include #textNodes also
    this.hasAttribute("replaceWith") && this.replaceWith(...shadowRoot.childNodes)
  }
})
<load-file src="//load-file.github.io/heart.svg">
  <!-- elements inside load-file are MOVED to shadowDOM -->
  <style shadowRoot>
    svg {
      height: 180px; /* Stack Overflow subwindow height */
    }
    path:nth-child(2n+2) {
      fill: GREEN; /* shadowDOM style does NOT style global DOM */
    }
  </style>
</load-file>
Danny '365CSI' Engelman
  • 16,526
  • 2
  • 32
  • 49
  • Wow this is quick, easy and has zero implementation problems (in comparison to other solutions, given my project characteristics). – Zefir Mar 17 '22 at 19:06
  • You should probably disclose that it is your own blog post. See e.g. *[Why am I getting push-back for linking to my own blog posts in answers?](https://meta.stackoverflow.com/a/278505)*, *[What is the policy for linking to your own blog in your answers?](https://meta.stackoverflow.com/questions/254280/)*, and *[Limits for self-promotion in answers](https://meta.stackexchange.com/questions/57497/)*. – Peter Mortensen Jan 12 '23 at 19:27
7

Here the fast and furious way :)

body {
    background-color: #DEFF05;
}

svg {
    width: 30%;
    height: auto;
}

svg path {
    color: red;
    fill: currentcolor;
}
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" id="Capa_1" x="0px" y="0px" viewBox="0 0 514.666 514.666"><path d="M514.666,210.489L257.333,99.353L0,210.489l45.933,19.837v123.939h30V243.282l33.052,14.274v107.678l4.807,4.453  c2.011,1.862,50.328,45.625,143.542,45.625c93.213,0,141.53-43.763,143.541-45.626l4.807-4.452V257.557L514.666,210.489z   M257.333,132.031L439,210.489l-181.667,78.458L75.666,210.489L257.333,132.031z M375.681,351.432  c-13.205,9.572-53.167,33.881-118.348,33.881c-65.23,0-105.203-24.345-118.348-33.875v-80.925l118.348,51.112l118.348-51.111  V351.432z"></path></svg>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ali Besharati
  • 918
  • 12
  • 25
  • 1
    why vote down !? this work well you can see it in the demo – Ali Besharati Feb 18 '21 at 10:56
  • 4
    Your answer explains nothing in contrast with others: https://stackoverflow.com/a/20720935/3795597 https://stackoverflow.com/a/30419873/3795597 https://stackoverflow.com/a/69397734/3795597 and countless others. It only works because you embed the svg in the main document. – MayeulC Jul 21 '22 at 16:00
7

If the same SVG must be used multiple times with different colors, define the set of paths within a hidden SVG which serves as the master copy. Then place new instances which refer to the master path with their individual fills.

Note: This approach only works with inline <svg> tags. It will not work with <img> tags loading .svg files.

:root {
  fill: gray;
}

.hidden {
  display: none;
}

svg {
  width: 1em;
  height: 1em;
}
<svg viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg" class="hidden">
 <path id="s_fave" d="m379 21c-57 0-104 53-123 78-19-25-66-78-123-78-74 0-133 68-133 151 0 45 18 88 49 116 0.5 0.8 1 2 2 2l197 197c2 2 5 3 8 3s5-1 8-3l206-206c2-2 3-3 5-5 0.8-0.8 1-2 2-3 23-28 35-64 35-102 0-83-60-151-133-151z"/>
 <path id="s_star" d="m511 196c-3-10-13-18-23-19l-148-13-58-137c-4-10-14-17-25-17-11 0-21 6-25 17l-58 137-148 13c-11 1-20 8-23 19-3 10-0.3 22 8 29l112 98-33 145c-2 11 2 22 11 28 5 3 10 5 16 5 5 0 10-1 14-4l127-76 127 76c9 6 21 5 30-1 9-6 13-17 11-28l-33-145 112-98c8-7 11-19 8-29z"/>
</svg>

<svg viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg"><use href="#s_fave"></use></svg>
<svg viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg"><use href="#s_star"></use></svg>
<svg viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg"><use href="#s_fave" fill="red"></use></svg>
<svg viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg"><use href="#s_star" fill="gold"></use></svg>
<svg viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg"><use href="#s_fave" fill="purple"></use></svg>
<svg viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg"><use href="#s_star" fill="silver"></use></svg>
<svg viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg"><use href="#s_fave" fill="pink"></use></svg>
<svg viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg"><use href="#s_star" fill="blue"></use></svg>
OXiGEN
  • 2,041
  • 25
  • 19
6

For example, in your HTML:

<body>
  <svg viewBox="" width="" height="">
    <path id="struct1" fill="#xxxxxx" d="M203.3,71.6c-.........."></path>
  </svg>
</body>

Use jQuery:

$("#struct1").css("fill", "<desired colour>");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Grv97
  • 81
  • 1
  • 1
  • 3
    This only works if you include the SVG file inline in the HTML. I've edited your answer to make this clear. – Flimm Oct 31 '19 at 14:48
6

Check out this code. It works.

<div>
   <!-- YouTube -->
   <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512">
       <path fill="white"
           d="M549.655 124.083c-6.281-23.65-24.787-42.276-48.284-48.597C458.781 64 288 64 288 64S117.22 64 74.629 75.486c-23.497 6.322-42.003 24.947-48.284 48.597-11.412 42.867-11.412 132.305-11.412 132.305s0 89.438 11.412 132.305c6.281 23.65 24.787 41.5 48.284 47.821C117.22 448 288 448 288 448s170.78 0 213.371-11.486c23.497-6.321 42.003-24.171 48.284-47.821 11.412-42.867 11.412-132.305 11.412-132.305s0-89.438-11.412-132.305zm-317.51 213.508V175.185l142.739 81.205-142.739 81.201z" />
   </svg>

   <!-- Instagram -->
   <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512">
       <path fill="white"
           d="M224.1 141c-63.6 0-114.9 51.3-114.9 114.9s51.3 114.9 114.9 114.9S339 319.5 339 255.9 287.7 141 224.1 141zm0 189.6c-41.1 0-74.7-33.5-74.7-74.7s33.5-74.7 74.7-74.7 74.7 33.5 74.7 74.7-33.6 74.7-74.7 74.7zm146.4-194.3c0 14.9-12 26.8-26.8 26.8-14.9 0-26.8-12-26.8-26.8s12-26.8 26.8-26.8 26.8 12 26.8 26.8zm76.1 27.2c-1.7-35.9-9.9-67.7-36.2-93.9-26.2-26.2-58-34.4-93.9-36.2-37-2.1-147.9-2.1-184.9 0-35.8 1.7-67.6 9.9-93.9 36.1s-34.4 58-36.2 93.9c-2.1 37-2.1 147.9 0 184.9 1.7 35.9 9.9 67.7 36.2 93.9s58 34.4 93.9 36.2c37 2.1 147.9 2.1 184.9 0 35.9-1.7 67.7-9.9 93.9-36.2 26.2-26.2 34.4-58 36.2-93.9 2.1-37 2.1-147.8 0-184.8zM398.8 388c-7.8 19.6-22.9 34.7-42.6 42.6-29.5 11.7-99.5 9-132.1 9s-102.7 2.6-132.1-9c-19.6-7.8-34.7-22.9-42.6-42.6-11.7-29.5-9-99.5-9-132.1s-2.6-102.7 9-132.1c7.8-19.6 22.9-34.7 42.6-42.6 29.5-11.7 99.5-9 132.1-9s102.7-2.6 132.1 9c19.6 7.8 34.7 22.9 42.6 42.6 11.7 29.5 9 99.5 9 132.1s2.7 102.7-9 132.1z" />
   </svg>
</div>

CSS

svg {
   fill: white;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Amit Bodaliya
  • 128
  • 2
  • 4
5

I found it a bit clumsy, but it is definitely a working way to dynamically change the color of an SVG included with <img> tag.

In the SVG file, you can add CSS content the following way:

<svg ...>
    <defs>
        <style>
            ...
        <style>
    <defs>

There you can use @media rules, with which the SVG can look outside itself for contextual circumstances. There's an aspect-ratio media feature that applies to the SVG box (e.g., the <img> tag). You can create different contexts for the SVG by stretching the SVG box a little bit.

This way you can also make the favicon the same SVG that appears on the website, but with a different color. (In this case, no other SVG boxes should be square-shaped.)

/* img stretched horizontally (if SVG is square-shaped) */
@media (min-aspect-ratio: 1000/999) {
    path {
        fill: blue;
    }
}

/* img stretched vertically (if SVG is square-shaped) */
@media (max-aspect-ratio: 999/1000) {
    path {
        fill: green;
    }
}

/* img with exact sizes */
@media (aspect-ratio: 86/74) {
    path {
        fill: red;
    }
}

/* favicon with light browser theme */
@media (aspect-ratio: 1/1) and (prefers-color-scheme: light) {
    path {
        fill: black;
    }
}

/* favicon with dark browser theme */
@media (aspect-ratio: 1/1) and (prefers-color-scheme: dark) {
    path {
        fill: white;
    }
}

One very important thing

The SVG must contain viewBox information, so that the stretching does not affect the graphics. Example:

<svg xmlns="http://www.w3.org/2000/svg" width="300" height="300" viewBox="0 0 300 300">
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bene Laci
  • 114
  • 1
  • 3
4

For a better resolution about Manish Menaria's (thank you so much for your help) response, use this filter generator instead a purposed generator: https://angel-rs.github.io/css-color-filter-generator/

.filter-green{
    filter: invert(48%) sepia(79%) saturate(2476%) hue-rotate(86deg) brightness(118%) contrast(119%);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kemot 90
  • 96
  • 4
3

If you want to do this to an inline SVG file, that is, for example, a background image in your CSS content:

background: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='rgba(31,159,215,1)' viewBox='...'/%3E%3C/svg%3E");

Of course, replace the ... with your inline image code.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Peter Kionga-Kamau
  • 6,504
  • 2
  • 17
  • 13
3

There are some problems with Manish Menaria's answer, if we convert white color it shows gray.

So I added some tweaks, and the below example specifically shows how to change the color in the material icon:

<mat-icon class="draft-white" svgIcon="draft" aria-hidden="false"></mat-icon>
.draft-white{
    filter: brightness(0) invert(1);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shabeer M
  • 160
  • 3
  • 9
3

You can use a font icon to use any CSS option in SVG

I was searching for a way to have any CSS options, like animation for SVG, and I ended up to generate a font icon with my SVG(s) and then used it inside a span (like Font Awesome), so any CSS option, like coloring, was available on it.

I used https://icomoon.io to convert my SVG image to a font icon. Then you can use it like Font Awesome or MaterialIcon inside HTML elements.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mahdi Khansari
  • 321
  • 4
  • 13
3

My answer would be this. But I’m not 100% sure if it works for everyone:

Select 'svg' and then 'path'. And you can change 'fill' then.

.eye-icon-container {
    width: 33px;
    height: 33px;
    border-radius: 5px;
    display: flex;
    justify-content: center;
    align-items: center;

    :hover {
      background-color: #ddf0ff;
    }
    :active {
      background-color: #1d398d;
      svg {
        path {
          fill: #fff;
        }
      }
    }
  }
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Evaldas
  • 169
  • 7
2

Actually, there is a quite more flexible solution to this problem: writing a Web Component which will patch SVG as text at runtime. I also published in a gist with a link to JSFiddle.

filter: invert(42%) sepia(93%) saturate(1352%) hue-rotate(87deg) brightness(119%) contrast(119%);

<html>

<head>
  <title>SVG with color</title>
</head>

<body>
  <script>
    (function () {
      const createSvg = (color = '#ff9933') => `
          <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="76px" height="22px" viewBox="-0.5 -0.5 76 22">
            <defs/>
              <g>
                <ellipse cx="5" cy="10" rx="5" ry="5" fill="#ff9933" stroke="none" pointer-events="all"/>
                <ellipse cx="70" cy="10" rx="5" ry="5" fill="#ff9933" stroke="none" pointer-events="all"/>
                <path d="M 9.47 12.24 L 17.24 16.12 Q 25 20 30 13 L 32.5 9.5 Q 35 6 40 9 L 42.5 10.5 Q 45 12 50 6 L 52.5 3 Q 55 0 60.73 3.23 L 66.46 6.46" fill="none" stroke="#ff9933" stroke-miterlimit="10" pointer-events="stroke"/>
              </g>
          </svg>`.split('#ff9933').join(color);

      function SvgWithColor() {
        const div = Reflect.construct(HTMLElement, [], SvgWithColor);
        const color = div.hasAttribute('color') ? div.getAttribute('color') : 'cyan';
        div.innerHTML = createSvg(color);
        return div;
      }

      SvgWithColor.prototype = Object.create(HTMLElement.prototype);
      customElements.define('svg-with-color', SvgWithColor);

      document.body.innerHTML += `<svg-with-color
        color='magenta'
      ></svg-with-color>`;

    })();

  </script>
</body>

</html>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Petr Tripolsky
  • 1,419
  • 15
  • 23
2

Use an svg <mask> element.

This is better than other solutions because:

  • Closely matches your original code.
  • Works in IE!
  • The embedded image can still be an external, unmodified file.
  • The image does not even have to be an SVG.
  • Color is inherited from font-color, so easy to use alongside text.
  • Color is a normal CSS color, not a strange combination of filters.

<svg style="color: green; width: 96px; height: 96px" viewBox="0 0 100 100" preserveAspectRatio="none">
  <defs>
    <mask id="fillMask" x="0" y="0" width="100" height="100">
      <image xlink:href="https://svgur.com/i/AFM.svg" x="0" y="0" width="100" height="100" src="ppngfallback.png" />
    </mask>
  </defs>
  <rect x="0" y="0" width="100" height="100" style="stroke: none; fill: currentColor" mask="url(&quot;#fillMask&quot;)" />
</svg>

https://jsfiddle.net/jamiegl/5jaL0s1t/19/

JamieGL
  • 1,392
  • 2
  • 9
  • 13
2

If you have a single-colour SVG with varying opacities that you simply want to tint to a different colour then there is another approach that can be used: the feFlood SVG filter.

This solution is not as straightforward as a single-line CSS, however:

  • It works on SVGs inside of an img element.
  • This doesn't require editing the source SVG at all.
  • It allows you to simply choose a target colour for the SVG and not worry about complex colour transforms, like hue-rotate.

Here is an example:

<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0">
  <defs>
    <filter id="recolourFilter" filterUnits="userSpaceOnUse">
      <feFlood flood-color="aquamarine" result="flood" />
      <feComposite in="flood" in2="SourceAlpha" operator="in" />
    </filter>
  </defs>
</svg>

<img style="filter: url(#recolourFilter);" width="300" src="https://upload.wikimedia.org/wikipedia/commons/6/6b/Bitmap_VS_SVG.svg" />

In the above example, we create an inline SVG to define the filters and then we apply it to the image. Inside of the <filter> block we first define the fill colour that we want via <feFlood> and then we create a composite image using the alpha channel of the source plus the flood colour. Finally, the filter is applied to the whole image via the filter CSS property on the img element.

I learned about this technique from this Smashing Magasine article. It's a highly recommended read if you want to learn more about SVG filters.

A few additional things to note:

  • This filter can be applied to any HTML element via the CSS filter property.
  • The same filter can be reused multiple times on the same page.
  • If you are using an inline SVG then the <defs> block can form part of the svg element and the filter can still be applied to the whole SVG or on selective elements. This avoids needing a separate SVG element for the filters.
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jens1101
  • 567
  • 7
  • 12
2

This took a while for me to workout, you can't change the colour of an imported svg (easily), how i managed to do and keep themes / colours from createStyles in my react application is like so:

<MURadio
  icon={
    <svg
      width="24px"
      height="24px"
      viewBox="0 0 24 24"
      version="1.1"
      xmlns="http://www.w3.org/2000/svg"
      style={{
        fillRule: "evenodd",
        clipRule: "evenodd",
        strokeLinejoin: "round",
        strokeMiterlimit: "2",
      }}
    >
      <g transform="matrix(1,0,0,1,-511.714,-525.038)">
        <g transform="matrix(1.04348,0,0,1.04348,511.192,523.902)">
          <circle cx="12" cy="12.589" r="11.5" style={{ fill: "white" }} />
          <path
            d="M12,1.089C18.347,1.089 23.5,6.242 23.5,12.589C23.5,18.936 18.347,24.089 12,24.089C5.653,24.089 0.5,18.936 0.5,12.589C0.5,6.242 5.653,1.089 12,1.089ZM12,2.089C6.205,2.089 1.5,6.794 1.5,12.589C1.5,18.384 6.205,23.089 12,23.089C17.795,23.089 22.5,18.384 22.5,12.589C22.5,6.794 17.795,2.089 12,2.089Z"
            className={classes.icon}
          />
        </g>
      </g>
    </svg>
  }
/>;
const useRadioButtonClasses = makeStyles<ITheme, IRadioButtonErrorProps>(
  (theme) =>
    createStyles({
      radio: { color: theme.mvf.palette.border },
      card: {
        height: '100%',
      },
      icon: ({ isError }) => ({
        fill: theme.mvf.palette.border,
        ...(isError && {
          fill: theme.mvf.palette.error,
        }),
      }),
      selectedRadioIcon: ({ isError }) => ({
        fill: theme.mvf.palette.primary.main,
        ...(isError && {
          fill: theme.mvf.palette.error,
        }),
      }),
...etc

I am assuming some level of knowledge, as this isn't full code, but MURadio is an v4 material ui radio button in use in our app, with the custom svg in one of the props by this material ui component - so you have change the default radio icon... and you can apply a theme colour to the custom radio icon (svg) dynamically, and as i am passing isError state like so const classes = useRadioButtonClasses({ isError }); so we can change the svg colour if there is an error.

Works for me and same setup (class.icon) as we style the regular components, hope it helps you.

Jeremy
  • 1,170
  • 9
  • 26
1

A good approach is to use a mixin to control stroke colour and fill colour. My 'svg's are used as icons.

@mixin icon($color, $hoverColor) {
    svg {
        fill: $color;

        circle, line, path {
            fill: $color
        }

        &:hover {
            fill: $hoverColor;

            circle, line, path {
                fill: $hoverColor;
            }
        }
    }
}

You can then do the following in your SCSS file:

.container {
    @include icon(white, blue);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
omarjebari
  • 4,861
  • 3
  • 34
  • 32
1

For Angular users, the "inline-svg-2" npm library was quite useful:

You can now dynamically configure your CSS colors, including with CSS variables, and the SVG will adapt.

Note: The "currentColor" trick works only for inlined SVGs, this is why we need a special module for this.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Benjamin Piette
  • 3,645
  • 1
  • 27
  • 24
1

if you are using svg with path then give fill color to path:

    svg path{
fill:red;
}
Tauseef Arshad
  • 583
  • 5
  • 13
0

I've found that Inkscape works really well. Unless you need an SVG in several colors, just make on in the color you need and use it.

After loading the image, select each path, change the color, save as a new SVG image.

-1

Simply add fill:"desiredColor" in the svg tag of the image: example:

<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="#bbb9c6">
<path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-2 12H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z"/><path d="M0 0h24v24H0z" fill="none"/></svg>
Shivani
  • 301
  • 5
  • 12
  • 1
    That's basically the same suggestion as [this answer](https://stackoverflow.com/a/50098855/1038015) or [this one](https://stackoverflow.com/a/27287453/1038015) – Robert Longson May 12 '20 at 05:23
  • those answers have mentioned fill in the path tag, it worked for me in the svg tag, hence i posted it – Shivani May 13 '20 at 06:53
-1

Works in Chrome last checked on August 2023

Just add a div with a class

<div class="icon"></div>

Then add this style to it

    .icon {
    -webkit-mask: url(SVG.svg);/*Your SVG file here*/
    mask: url(SVG.svg) ;
    background-color: blue; /* Or any color of your choice. */
    width: 200px !important;
    height: 200px !important;
   }
cr7 aj7
  • 101
  • 1
  • 6
-2

Open your image using a browser, right-click on the image click on view page source and you will see the svg tag of the image. Cope and paste into your html, then change the fill to the colour of your choice

  • 2
    The [accepted answer](https://stackoverflow.com/a/22253046/1038015) already suggests inlining and then setting the colour as the solution. – Robert Longson May 12 '20 at 05:28
-2

You shall not set the color directly on the SVG image, if you want to program the color of the SVG.

In 2021, you can use the following CSS content to make the color change.

html {
  --iron-icon-fill-color-1: green;
  --iron-icon-fill-color-2: red;
  --iron-icon-stroke-color: white;
}


svg#icon-green {
  fill: var(--iron-icon-fill-color-1, currentcolor);
  stroke: var(--iron-icon-stroke-color, none);
}

svg#icon-red {
  fill: var(--iron-icon-fill-color-2, currentcolor);
  stroke: var(--iron-icon-stroke-color, none);
}

svg#icon {
  fill: var(--iron-icon-fill-color-x, currentcolor);
  stroke: white;
}
<html>
<body>
<svg id="icon-green" xmlns="http://www.w3.org/2000/svg" width="40px" height="40px" style="vertical-align:text-bottom" viewbox="0 0 40 40">
  <circle cx="20" cy="20" r="18" stroke-width="3"/>
  <path d="M 10,10 30,30 M 10,30 30,10" fill="none"  stroke-width="6"/>
</svg>


<svg id="icon-red" xmlns="http://www.w3.org/2000/svg" width="40px" height="40px" style="vertical-align:text-bottom" viewbox="0 0 40 40">
  <circle cx="20" cy="20" r="18" stroke-width="3"/>
  <path d="M 10,10 30,30 M 10,30 30,10" fill="none"  stroke-width="6"/>
</svg>

<svg id="icon" xmlns="http://www.w3.org/2000/svg" width="40px" height="40px" style="vertical-align:text-bottom" viewbox="0 0 40 40">
  <circle cx="20" cy="20" r="18" stroke-width="3"/>
  <path d="M 10,10 30,30 M 10,30 30,10" fill="none"  stroke-width="6"/>
</svg>

</body>

</html>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Chester Fung
  • 182
  • 1
  • 10
-2

My usage is with Bootstrap icons, copying your SVG path.

span{
    path{
        color: red;
    }
}

One example of SVG Bootstrap:

        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
          class="bi bi-exclamation-octagon" viewBox="0 0 16 16">
          <path
            d="M4.54.146A.5.5 0 0 1 4.893 0h6.214a.5.5 0 0 1 .353.146l4.394 4.394a.5.5 0 0 1 .146.353v6.214a.5.5 0 0 1-.146.353l-4.394 4.394a.5.5 0 0 1-.353.146H4.893a.5.5 0 0 1-.353-.146L.146 11.46A.5.5 0 0 1 0 11.107V4.893a.5.5 0 0 1 .146-.353L4.54.146zM5.1 1 1 5.1v5.8L5.1 15h5.8l4.1-4.1V5.1L10.9 1H5.1z" />
          <path
            d="M7.002 11a1 1 0 1 1 2 0 1 1 0 0 1-2 0zM7.1 4.995a.905.905 0 1 1 1.8 0l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 4.995z" />
        </svg>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
elver
  • 103
  • 1
  • 9
-3

If you want to use CSS to change the colour, you could also use an online tool like this one: Change SVG Color Using CSS Filter

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Prottay
  • 385
  • 5
  • 9
  • 2
    That answer is uninformative, it doesn't explain how to do it, nor that it's an svg filter. It would be better to comment on the top-voted answer and provide a link to that tool, which is an alternative to the codepen. – MayeulC Jul 21 '22 at 16:13
-3

The easiest trick is to change the color using jQuery on page load.

      $(document).ready(function () { 
              $('svg').find('path').attr('fill', '#FFF');
      });

#FFF is the color code that you want to set.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
symi khan
  • 465
  • 5
  • 9
  • This is a rather convoluted approach. But it can be used if you don't have access to actually change the SVG directly in the code. – benjaminhull Mar 07 '22 at 12:33
  • & This code also useful if element loads after ajax request completion or in ajax response – symi khan Dec 06 '22 at 17:01
-3

You can change the svg color using fill attribute

<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0" fill="#colorcode">
    Your svg path here
</svg>

Check demo here

Kabeer
  • 117
  • 1
  • 4
  • 2
    Obviously, but please **read the original question** as well as the **previous (39) answers** before adding a new answer. You can't apply `fill` to `` or `` elements. – herrstrietzel Feb 10 '23 at 05:14
  • You know its the wrong way to add svg. Who asked this question already know this question is just waste of time but he asked this question. He can ask that type of question and i can't add answer in the right way. – Kabeer Feb 11 '23 at 20:44
  • There are many ways to attach and handle svgs – sometimes you might be restricted by a certain environment (CMS, framework, library etc.). I don't blame you, since there are a lot of answers in this thread **completely ignoring** the OP's questions. However, you should always refer to the initial problem and if not exactly solving the issue explain, why the OP should concider to choose an alternative approach (like inlined svg, use native web-components, external `` references or even icon fonts etc.). – herrstrietzel Feb 12 '23 at 00:43
  • 1
    Please make sure, your answer adds a **new and unique approach/insight** to the thread. Assuming that the OP should know that his approach is not working - that is not very helpful. BTW. I haven't downvoted, since I'm more interested in encouraging new contributors to improve their answers. Please prefer code examples via SO's snippets - hosted snippets might expire. – herrstrietzel Feb 12 '23 at 00:43
-4

The shortest Bootstrap-compatible way, no JavaScript:

.cameraicon {
    height: 1.6em; /* Set your own icon size */
    mask: url(/camera.svg); /* Path to your image */
   -webkit-mask: url(/camera.svg) no-repeat center;
}

And use it like:

<td class="text-center">
    <div class="bg-secondary cameraicon"/><!-- "bg-secondary" sets actual color of your icon -->
</td>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Wolfrevok Cats
  • 167
  • 1
  • 7