Fill currentcolor не работает

Cascading SVG Fill Color

Take your JavaScript to the next level at Frontend Masters.

One time someone told me their biggest problem with SVG icons is that they didn’t match the color of text they were by. In fact it was such a big problem for them, that despite seeing the advantages of SVG icons they were sticking with icon fonts. I didn’t think of it at the time, but there is a pretty easy solution for this.

The idea is to use the currentColor value in CSS to pass that text color through to the SVG shapes. For instance:

You can simplify this and let the fill cascade to the SVG:

So fill cascades eh? Pretty neat. Why don’t we just do this then if it’s that easy:

fill only affects SVG anyway, so it won’t be doing anything we don’t want it to do, and it’s easily overridable by a more specific selector anyway.

The trouble is that doesn’t quite work as is.

Take this example, which is just our original example inside the :

What is the currentColor at the ? blue , right? Because color cascades (is inherited). We can see that’s true, because the border on that svg will be blue. But the icon itself (which is really a drawn

It’s not a huge deal though, because you can just:

And that will ensure it snags the color from whatever you would normally expect it to. You can also apply the fill to the use, path, symbol, circle, rect, etc, but hitting the svg just kinda covers it all (which is nice for simple one-color use cases).

See the Pen lcDBd by Chris Coyier (@chriscoyier) on CodePen.


Can’t control SVG icon fill color with CSS styles

I have read all post in here about styling my svg fill color with CSS but without luck.

What I want is to able to make an icon with a link. My external svg file is grey, but I would like to make it red with css and change color to yellow when hovering.

I think I am targeting the SVG wrong. Please help. My test is here: testpage

2 Answers 2

Answer a little overdue, but worth having for reference for others.

Basically, the only type of SVG usage which can be used in conjunction with CSS is the inline usage.

This means you would literally put your SVG markup directly into the HTML source as follows:

NOTE: This SVG has been optimised using SVGO and then manually edited to include and ID

You can now control the SVG using CSS like so:


You can also use the currentColor keyword in the SVG to apply a colour to certain elements of it, for example:

This can be handy if you need to use the same SVG across different websites / themes, such as dark and light, for easily switching SVG colours with CSS.

Caching / performance consideration: SVG cloning

You should also keep in mind, it’s not a good idea to use inline SVG for repetitive images, such as icons, because they can not be cached (the SVG code will be repeated throughout your HTML, increasing the ultimate file size).

Instead, one approach I like to use is to create an SVG index at the top of my page, which contains all the SVGs I want to use on the page, for example:

Make sure you set the SVG index to display: none so it doesn’t show up on the page.

Читайте также:  Как правильно настроить либре офис

You can now reuse these SVGs repetitively throughout the page using the xlink:href attribute as follows:

This is called cloning, and allows you to take advantage of cacheable SVGs which can be controlled with CSS!



doctor Brain

мир глазами веб-разработчика

CSS: currentColor для svg

возможности использования ключевого слова currentColor для svg-изображений

время чтения 3 мин.

Несколько дней назад Вы могли прочитать статью о использовании ключевого слова currentColor для создания расширяемых компонентов — “CSS: currentColor”. Однако, currentColor можно применять и для svg-изображений.

fill для SVG

Допустим, есть монохромное svg-изображение, и Вы хотите, чтобы оно было одинакового цвета с основным текстом.

Возьмем картинку с деревом (

Если атрибуты fill и stroke не определены, дерево будет черным (#000000) — это цвет по умолчанию.

Например, цвет текста на сайте “темно-угольный” (#272727), если Вы хотите, чтобы svg-изображение было такого же цвета, нужно задать соответствующее значение цвета для атрибута fill тега path :

Динамический цвет для SVG

Вышеприведенный подход несомненно работает. Но как поступить, если возникнет необходимость добавить такую картинку в параграф с текстом другого цвета например, зеленого.

Это мой зеленый текст

В данном случае цвет текста #009900. Вам придется еще раз изменить значение параметра fill для изображения:

Теперь картинка и текст одного цвета. А что делать, если это будет ссылка: при наведении цвета опять не будут совпадать.

Именно в таких случаях ключевое слово currentColor будет Вашим спасением. Его можно использовать в качестве значения атрибута fill : цвет svg-картинки будет соответствовать цвету текста:

Это очень хороший и, что важно, очень востребованный трюк.

Когда не нужно использовать currentColor

В некоторых случаях использование значения currentColor для атрибута fill неуместно. Например, если изображение является логотипом и должно сохранять свой специфический цвет независимо от контекста и действий, совершаемых на сайте.


SVG Fill Color Not Working

I’m new to using SVGs and can’t figure out what I’m doing wrong here. For most of them, if I want to change the color, I use:

But for this one — and other’s I’ve come across — for some reason this way doesn’t work.

7 Answers 7

you can just add !important beside fill

Your path has inline css on it with fill. This overrides your other css. Can be fixed with !important. Or you could remove the inline css.

If you are not in control of your SVG, (perhaps because it comes from an external source you are re-theming,) you are stuck using !important to override the SVG fill property.

If your SVG is in your code base, it is much better to set fill=»currentColor» , and then set the CSS color property.

As much as possible, try to avoid using !important . Instead, try to make your selectors more specific. Remember inline takes precedence over id , which takes precedence over classes, which takes precedence over elements.

Your solution may be as simple as adding an additional class, or in the case of a single element, an id .

For a more detailed explanation please read this article

If you have access to the svg internal code, just set the path to fill=»currentColor» and then set the regular color prop, not fill prop in the parent svg, eg:

I couldn’t get any display of CSS SVG until I discovered, quite by accident, that the quotation marks for an attribute value in SVG are not optional, as they are in HTML for values not containing spaces. Also, a hex value, like fill=»#00BB00″ , will not work for me, even using the fill=»currentColor» advice ( fill=»green» does work). Finally, if you use «url()» in the CSS, you can’t include newlines or omit the xmlns attribute.

Читайте также:  Как настроить нвидиа шилд тв

Not the answer you’re looking for? Browse other questions tagged css svg or ask your own question.



Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.10.15.40479

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.


Fill color doesn’t work for background SVG images #26


equinusocio commented Jul 3, 2018 •

Hi, just to tell you that this point in the readme is not totally true. You should specify that there are many techniques to define and use icons. You can use svg in different ways and modify his color, even on IE9+. Icon fonts are now considered hacks since there are many approaches with a more specific technology.

1. Mask

2. As plain svg background

3. Using filters on a 50% gray icon.

4. Using currentColor

5. External svg sprite and background

You can combine this with other methods.

The text was updated successfully, but these errors were encountered:

jantimon commented Jul 3, 2018 •

If I am correct none of the examples allows to use the currentColor for the svg in IE 9+ for a non inlined svg.

1.) Won’t work in IE11 https://caniuse.com/#feat=css-masks
2.) Can’t be combined with currentColor
3.) Can’t be combined with currentColor — and also hard to maintain (what color might 220deg)
4.) Can’t be combined with pseudoElements
5.) Can’t be combined with currentColor

equinusocio commented Jul 3, 2018 •

@jantimon currentColor is supported on IE9+. You can put an inlined svg with the fill set to currentColor

jantimon commented Jul 3, 2018 •

@equinusocio could you please let me know if any of your approaches allows to use the currentColor for the svg in IE 9+ for a non inlined svg?

With non-inlined I mean a pure css solution which does not require an additional svg element in the html.

equinusocio commented Jul 3, 2018 •

@jantimon No but the point of my issue is not «using only background» (i wrote «You can use svg in different ways and modify his color, even on IE9+«). The point of the readme talk about the impossibility to change the icon color if you use svg as background image (so it’s not related to IE9)..the key here is that svg can be used in multiple ways and not only as background. This not means that svg fonts are a good replacement (it is useful only for the IE 9+ support) but for modern browser there are alot better ways.

If someone want to use icons there are many modern approaches to use them and then just go for a graceful-degradation. If you really need to support such older browsers instead to overload the css weight with inlined fonts users can just provide a fallback with one line of css.

The last two points..

  • Fill color doesn’t work for background SVG images
  • Inline SVGs are resolved relative to the page not to the css
Читайте также:  Не нужно работать над отношениями

..are not minus or directly related to «why use fonts over svgs.» and they are misleading. I think they should be removed from that section. 🙂

jantimon commented Jul 3, 2018

Okay than I got you wrong — I though you had a better approaches if you want to target all common browsers.

Why do you think Fill color doesn’t work for background SVG images is not true as long as IE11 has to be supported in many web projects?

I used this approach for a pattern library which was used on multiple domains.
The consumers just added the css file and all icons worked because all paths are relative to the css.
Why do you think that’s wrong?

equinusocio commented Jul 3, 2018 •

They are both correct! But these key points are not related (in my opinion) to choosing fonts over svgs (or the «When should you use icon fonts over pure SVGs?» title is misleading).

The first one is a minus only if you use svg’s as background, but it’s not an svg limitation, it is just one of many ways to use svg’s (not even with normal images you can manipulate them). It’s same as telling that if you use fonts you can’t manipulate icons paths with css animations (a thing that you can do with plain svg) :). These are just choises that doesn’t not reflect minus or plus.

I just think you should not tell when to choose which one, but let user know about all limitation (both svg and fonts) and not telling only the fonts advantages. Right now the readme does not tell the full truth 🙂

This is just my opinion. Sorry, english is not my language but i’m here in peace 😀 feel free to close this issue.

jantimon commented Jul 6, 2018 •

@equinusocio I really like your first solution as it is a full replacement for all requirements the iconfont-webpack-plugin is trying to address.

We could add a new option which might be legacyBrowserSupport which is set to true by default and switch to your svg-mask approach if set to false .

We would have to measure the size of the svg to have the correct height/width ratio and translate it to em to achieve the exact same effect you would have with icon font glyphs.

That way people could use svgs for modern browsers and fallback to icon-fonts if needed.
Would you be interested in working on that?

equinusocio commented Jul 7, 2018

I’m not a javascript developer 😅 i don’t know if i can really help you. I’m focused on html / css architectures.

Btw, using the mask approach the svg size should not be computed. These sizes are relative to the element box or can be pixels. So the user should be able to declare these sizes

jantimon commented Jul 8, 2018

To bad 🙁
If we would use EM the size could easily be set using a font-size.

Overall this would work very similar to the legacy solution

equinusocio commented Jul 8, 2018

Intead to use the shorthand expression the user can just set background-size and use font size for text

jantimon commented Jul 9, 2018

Hm it sounds like you don’t understand what I mean — should I explain what the iconfont-webpack-plugin actually does?